我最近一直在学习C#中的对象初始化器,但现在我想知道当它与构造函数发生冲突时它是如何工作的。
public class A
{
public bool foo { get; set; }
public A()
{
foo = true;
}
public A(bool bar)
{
foo = bar;
}
}
当我尝试这个时会发生什么?
public class B
{
private A a = new A() { foo = false };
private A b = new A(true) { foo = false };
}
构造函数中的默认值是否是让 bool
开始为真且可以更改的好方法?
public A(bool bar = true)
{
foo = bar;
}
最佳答案
来自documentation :
The compiler processes object initializers by first accessing the default instance constructor and then processing the member initializations.
这意味着在最简单的情况下(命名对象初始化),它基本上是调用默认构造函数然后调用属性 setter 的简写(或语法糖)。在匿名类型的情况下,这种初始化实际上是必需的,而不仅仅是糖。
对于问题的第二部分:更多的是样式问题,但如果您有关键属性,我不会创建具有默认值的构造函数。让客户端代码明确设置值。我也不确定为什么要这样做:b = A(true) {foo = false};
是个好主意,除非你参加代码混淆比赛。
不过要小心:
... if the default constructor is declared as private in the class, object initializers that require public access will fail.
关于c# - C# 中的构造函数与对象初始值设定项优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17327266/