一:构造函数的使用
当我们需要对一个类中的字段进行初始化时,可以这样做:
显然很麻烦,使用构造函数可以简单很多:
class Weapon
{
public int id;
public string name;
public int price;
public Weapon()
{
Console.WriteLine("无参构造函数被调用");
}
public Weapon(int id, string name, int price)
{
this.id = id;
this.name = name;
this.price = price;
}
}
class Test
{
static void Main(string[] args)
{
Weapon w1 = new Weapon(); //无参构造函数被调用
Weapon w2 = new Weapon(1001, "短剑", 150);
Console.WriteLine($"编号:{w2.id},名称:{w2.name},价格:{w2.price}"); //编号:1001,名称:短剑,价格:150
}
}
二:构造函数的继承
public class Item
{
public string id;
public string name;
public Item(string id, string name)
{
this.id = id;
this.name = name;
}
}
public class Weapon : Item
{
public int atk;
public Weapon(string id, string name, int atk) : base(id, name)
{
}
}
三:总结
——构造函数没有返回值
——一个类中可以有多个构造函数 ,可根据其参数个数的不同或参数类型的不同来区分它们,这称作构造函数的重载
——构造函数的命名必须和类名完全相同
——调用子类的构造函数时会先调用父类的无参构造函数
——构造函数不能被直接调用,必须通过new关键字在创建对象时才会自动被调用
——当一个类没有定义任何构造函数,C#编译器会为其自动生成一个默认的隐式无参构造函数
如果一个类中已经定义了有参构造函数,实例化的时候需要调用无参构造函数则必须定义一个显式的无参构造函数