1. 程式人生 > >C#基礎:結構體的簡單使用

C#基礎:結構體的簡單使用

  1. struct Weapon {//武器結構體
  2.             //欄位只能宣告,不能有初始值
  3.             public string name;//武器名字
  4.             public int physicalDefense;//物理防禦
  5.             public int maxHp;//最大血量
  6.             //結構體建構函式,只能宣告帶引數的建構函式,不能宣告預設無參建構函式。但是預設構造一直存在。
  7.             public Weapon(string name,int physicalDefense,int maxHp) {//初始化欄位
  8.                     this.name = name;
  9.                     this.physicalDefense = physicalDefense;
  10.                     this.maxHp = maxHp;
  11.             }
  12.         }
  13. class Program{
  14.        static void Main(string[] args){
  15.              Weapon wp = new Weapon();//呼叫預設建構函式
  16.             Weapon wap = new Weapon("石像鬼板甲",50,400);//有參建構函式
  17.             wp.name = "暴風大劍";
  18.             wp.physicalDefense = 20;
  19.             wp.maxHp = 0;
  20.             Console.WriteLine(wp.name);
  21.             Console.WriteLine(wp.physicalDefense);
  22.             Console.WriteLine(wp.maxHp);
  23.             Console.WriteLine("----------");
  24.             Console.WriteLine(wap.name);
  25.             Console.WriteLine(wap.physicalDefense);
  26.             Console.WriteLine(wap.maxHp);
  27.       }
  28. }