集合类型属性的设置器

2024-03-11

集合类型属性是否需要设置器

//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; }
       }
  }

何时使用类型 1 和类型 2? 如果我初始化一个 List 并使用只读属性 Customers 还不够吗?如Company.Customers.Add(new Customer)

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


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

它包含很好的建议:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

集合类型属性的设置器 的相关文章

随机推荐