【发布时间】:2020-09-04 21:30:34
【问题描述】:
我通常在构造函数的参数中声明一个可选参数(默认值),如下所示:
public class XV
{
public XV(int startPosition = 1) // Constructor
{
this.StartPosition = startPosition;
}
public int StartPosition { get; set; } // Property
}
但后来我发现自己正在查看我这样编写的旧代码:
public class XV
{
public XV( ... ) { ... } // Constructor
public XV(int startPosition) // Constructor
{
this.StartPosition = startPosition;
}
public int StartPosition { get; set; } = 1; // Property
}
与在构造函数中创建可选值相比,将= 1 添加到属性有什么用处?
是否只是为了支持构造函数中不存在的属性的默认值?
但如果是这样,为什么不在这种情况下将它们添加到构造函数中呢?
【问题讨论】:
-
有些类有很多属性。如果您要将所有属性放入具有默认值的 ctor 中,这可能会变得混乱。此外,如果您只想为最后一个参数指定一个新值,则必须声明它之前的所有参数。
-
另一个原因是可选参数仅支持“编译时常量”。例如这是非法的
public XV(List<int> nums = new List<int>(){1,2,3}),这没问题public List<int> Nums { get; set; } = new List<int>() { 1, 2, 3 }; -
What is the use of adding = 1 to the Property compared to creating an optional value in the Constructor?因为属性本身的默认值适用于所有构造函数。
标签: c# properties default-value optional-parameters