我有以下简单的类:
public class SimpleClass{
public int SimpleProperty {get; set;}
public SimpleClass(){
}
}
当我创建 SimpleClass 的实例时,我需要将属性 SimpleProperty 初始化为默认值。 这样做的最好方法是什么?
在构造函数中创建参数并在创建简单类实例时传递默认值:
public class SimpleClass{ public int SimpleProperty {get; set;} public SimpleClass(int simpleProperty){ SimpleProperty = simpleProperty; } }
或在默认构造函数中初始化属性:
public class SimpleClass{ public int SimpleProperty {get; set;} public SimpleClass(){ SimpleProperty = 0; //the example of default value } }
最佳答案
好吧,这在很大程度上取决于您正在处理的项目。
如果它是大型企业项目,并且您的属性是某种对象类型(这使您的类依赖于其他对象),第一个选项会更可取,因为它允许使用 IoC 容器和框架,并且它还简化了单元测试的编写方式,因为在 ctor 内部传递模拟值很简单,如果 ctor 不接受参数,则不那么简单。
对于简单类型,如 int
或在一个简单的宠物项目中,但这并不重要,由您决定。不要忘记,您可以为 ctor 使用可选参数:
public SimpleClass(int simpleProperty = 15)
{
SimpleProperty = simpleProperty;
}
关于c# - 当创建类的实例时,使用默认值初始化类属性的方法更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39530461/