2011-04-21 58 views
3

当还使用自动属性时,是否有办法使用收集初始值设定项?具有自动属性的收集初始值设定程序

// Uses collection initializer but not automatic properties 
private List<int> _numbers = new List<int>(); 
public List<int> Numbers 
{ 
    get { return _numbers; } 
    set { _numbers = value; } 
} 


// Uses automatic properties but not collection initializer 
public List<int> Numbers { get; set; } 


// Is there some way to do something like this?? 
public List<int> Numbers { get; set; } = new List<int>(); 
+1

[默认值自动属性的可能重复](http://stackoverflow.com/questions/4691888/automatic-property-with-default-value) – AakashM 2011-04-21 20:11:12

回答

4

不,基本上。你将不得不在构造函数中初始化集合。说实话,一个可设置的集合很少是一个好主意无论如何;我实际上只使用(改变你的第一个版本,去掉set):

private readonly List<int> _numbers = new List<int>(); 
public List<int> Numbers { get { return _numbers; } } 

,或者如果我想推迟施工,直到第一次访问:

private List<int> _numbers; 
public List<int> Numbers { 
    get { return _numbers ?? (_numbers = new List<int>()); } 
} 
1

// Is there some way to do something like this??

public List<int> Numbers { get; set; } = new List<int>();

号你有一个明确定义的构造函数初始化,有没有现场初始化招数适用于此。

此外,这与收集初始化无关。您也无法初始化

public object Foo { get; set; } 

以外的构造函数。

相关问题