C#中的构造函数

一:构造函数的使用

当我们需要对一个类中的字段进行初始化时,可以这样做:

显然很麻烦,使用构造函数可以简单很多:

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#编译器会为其自动生成一个默认的隐式无参构造函数
如果一个类中已经定义了有参构造函数,实例化的时候需要调用无参构造函数则必须定义一个显式的无参构造函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hello Bug.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值