集合类型属性的setter

集合类型属性是否必需的setter

//Type 1 class Company { private IList customers; public IList Customers { get { return customers; } set { customers = value; } } } //Type 2 class Company { private readonly IList customers = new List(); public IList Customers { get { return customers; } } } 

我什么时候使用Type 1和Type 2? 如果我初始化List并使用readonly属性Customers,那还不够吗? 如在Company.Customers.Add(new Customer)

为集合类型属性提供setter的最佳实践是什么?

请阅读FxCop重新安装CAS2227“集合属性应该只读” http://msdn.microsoft.com/en-us/library/ms182327(VS.80).aspx

它包含很好的建议:)

不一般(我通常不添加它们),但如果你想使用XmlSerializer ,它们是必需的。 这是一种痛苦。 它也必须是具体类型(例如ListT[] – 而不是IList )。 幸运的是, DataContractSerializer并没有遭受同样的命运。

我更喜欢

 public IList Customers { get; private set; } 

但这个要求

 this.Customers = new List(); 

Company构造函数中