3 回答

TA贡献1804条经验 获得超7个赞
您可以通过类的构造函数来实现:
public class foo {
public foo(){
Bar = "bar";
}
public string Bar {get;set;}
}
如果您有另一个构造函数(即使用参数的构造函数)或一堆构造函数,则可以始终使用此构造函数(称为构造函数链接):
public class foo {
private foo(){
Bar = "bar";
Baz = "baz";
}
public foo(int something) : this(){
//do specialized initialization here
Baz = string.Format("{0}Baz", something);
}
public string Bar {get; set;}
public string Baz {get; set;}
}
如果您始终将调用链接到默认构造函数,则可以在那里设置所有默认属性初始化。链接时,链接的构造函数将在调用构造函数之前被调用,以便您更专业的构造函数将能够在适用时设置不同的默认值。

TA贡献1810条经验 获得超4个赞
在默认构造函数中(当然也可以在任何非默认构造函数中):
public foo() {
Bar = "bar";
}
我相信这与原始代码的性能一样好,因为无论如何这都是幕后发生的事情。
- 3 回答
- 0 关注
- 724 浏览
添加回答
举报