您可以使用标准语法(使用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 };