C#基础:结构体的简单使用

定义结构体使用关键字struct.

结构体是值类型,是一种自定义数据类型。

示例代码如下:

  1. struct Weapon {//武器结构体
  2.             //字段只能声明,不能有初始值
  3.             public string name;//武器名字
  4.             public int physicalDefense;//物理防御
  5.             public int maxHp;//最大血量
  6.  
  7.             //结构体构造函数,只能声明带参数的构造函数,不能声明默认无参构造函数。但是默认构造一直存在。
  8.             public Weapon(string name,int physicalDefense,int maxHp) {//初始化字段
  9.                     this.name = name;
  10.                     this.physicalDefense = physicalDefense;
  11.                     this.maxHp = maxHp;
  12.             }
  13.         }
  14. class Program{
  15.        static void Main(string[] args){
  16.              Weapon wp = new Weapon();//调用默认构造函数
  17.             Weapon wap = new Weapon("石像鬼板甲",50,400);//有参构造函数
  18.             wp.name = "暴风大剑";
  19.             wp.physicalDefense = 20;
  20.             wp.maxHp = 0;
  21.             Console.WriteLine(wp.name);
  22.             Console.WriteLine(wp.physicalDefense);
  23.             Console.WriteLine(wp.maxHp);
  24.             Console.WriteLine("----------");
  25.             Console.WriteLine(wap.name);
  26.             Console.WriteLine(wap.physicalDefense);
  27.             Console.WriteLine(wap.maxHp);
  28.       }
  29. }

猜你喜欢

转载自blog.csdn.net/QQhelphelp/article/details/83539637