您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在C#中进行构造函数链接

如何在C#中进行构造函数链接

您可以使用标准语法(使用this类似方法方法)在类 选择重载:

class Foo 
{
    private int id;
    private string name;

    public Foo() : this(0, "") 
    {
    }

    public Foo(int id, string name) 
    {
        this.id = id;
        this.name = name;
    }

    public Foo(int id) : this(id, "") 
    {
    }

    public Foo(string name) : this(0, name) 
    {
    }
}

然后:

Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");

另请注意:

对于“为什么?”:

SomeBaseType(int id) : base(id) {...}

请注意,您也可以以类似的方式使用对象初始化程序(无需编写任何内容):

SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
         z = new SomeType { DoB = DateTime.Today };
c# 2022/1/1 18:14:48 有439人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶