4

到目前为止,我见过的最短的代码声明一个只能从我见过的类内部设置的属性是:

public T Property {get; private set;} 

但是如果我想用一个起始值声明它(这不是该类型的默认值),我该怎么做呢?

实际上我正在这样做:

public T Property {get; private set;}
private void Initialize() {Property = Value; }

另一种选择是:

private T _Property = Value;
public property {get {return _Property;}}

但是我想知道我是否可以只用一个代码行来编写它,因为我将编写许多这样的属性,而且我不想为每个属性都有一个重复的行。

4

1 回答 1

4

Nope. Auto-properties always default to their default value.

Your best bet is to set them in the constructor, or else just not use an auto-property.

public T Property {get; private set;}
public MyClass() {
   Property = Value; 
}
于 2013-05-08T17:29:08.943 回答