集合类型属性是否需要 setter

//Type 1
class Company
{
    private IList<Customer> customers;

    public IList<Customer> Customers
    {
        get { return customers; }
        set { customers = value; }
    }
}

 //Type 2
 class Company
 {
       private readonly IList<Customer> customers = new List<Customer>();

       public IList<Customer> Customers
       {
               get { return customers; }
       }
  }

我什么时候使用 Type 1 和 Type 2 ?
如果我初始化一个 List 并使用只读属性 Customers 是不是就足够了?就像在 Company.Customers.Add(new Customer) 中一样

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

最佳答案

请阅读 FxCop 推荐 CAS2227“集合属性应为只读”
http://msdn.microsoft.com/en-us/library/ms182327(VS.80).aspx

它包含很好的建议:)

关于c# - 集合类型属性的 setter ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/669066/

10-11 23:04
查看更多