C#基礎:結構體的簡單使用
阿新 • • 發佈:2018-12-18
- struct Weapon {//武器結構體
- //欄位只能宣告,不能有初始值
- public string name;//武器名字
- public int physicalDefense;//物理防禦
- public int maxHp;//最大血量
- //結構體建構函式,只能宣告帶引數的建構函式,不能宣告預設無參建構函式。但是預設構造一直存在。
- public Weapon(string name,int physicalDefense,int maxHp) {//初始化欄位
- this.name = name;
- this.physicalDefense = physicalDefense;
- this.maxHp = maxHp;
- }
- }
- class Program{
- static void Main(string[] args){
- Weapon wp = new Weapon();//呼叫預設建構函式
- Weapon wap = new Weapon("石像鬼板甲",50,400);//有參建構函式
- wp.name = "暴風大劍";
- wp.physicalDefense = 20;
- wp.maxHp = 0;
- Console.WriteLine(wp.name);
- Console.WriteLine(wp.physicalDefense);
- Console.WriteLine(wp.maxHp);
- Console.WriteLine("----------");
- Console.WriteLine(wap.name);
- Console.WriteLine(wap.physicalDefense);
- Console.WriteLine(wap.maxHp);
- }
- }