我知道这应该是一个 super 简单的问题,但一段时间以来我一直在为这个概念苦苦挣扎。
我的问题是,如何在 C# 中链接构造函数?
我正在上我的第一个 OOP 类(class),所以我只是在学习。我不明白构造函数链接是如何工作的,或者如何实现它,甚至不明白为什么它比只做没有链接的构造函数更好。
我希望能提供一些带有解释的示例。
那么如何链接它们呢?
我知道有两个就可以了:
public SomeClass this: {0}
public SomeClass
{
someVariable = 0
}
但是如何用三、四等来实现呢?
同样,我知道这是一个初学者问题,但我很难理解这一点,但我不知道为什么。
最佳答案
您使用标准语法(像方法一样使用 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");
另请注意:
- 您可以使用
base(...)
链接到基类型上的构造函数
- 你可以在每个构造函数中加入额外的代码
- 默认(如果您未指定任何内容)是
base()
对于“为什么?”:
- 减少代码(总是一件好事)
必需调用非默认的基础构造函数,例如:
SomeBaseType(int id) : base(id) {...}
请注意,您也可以以类似的方式使用对象初始值设定项(无需编写任何内容):
SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
z = new SomeType { DoB = DateTime.Today };
关于c# - 如何在 C# 中进行构造函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1814953/