定义结构体使用关键字struct.
结构体是值类型,是一种自定义数据类型。
示例代码如下:
- 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);
- }
- }