【问题标题】:Setters for collection type properties集合类型属性的设置器
【发布时间】:2009-03-21 10:03:06
【问题描述】:

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

//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)

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

【问题讨论】:

    标签: c# oop collections


    【解决方案1】:

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

    它包含了很好的建议:)

    【讨论】:

      【解决方案2】:

      一般不会(而且我通常不会添加它们),但如果您想使用XmlSerializer,它们是必需的。这是一种痛苦。它还必须是具体类型(例如 List&lt;T&gt;T[] - 而不是 IList&lt;T&gt;)。幸运的是,DataContractSerializer 没有遭受同样的命运。

      【讨论】:

      • 我很想知道为什么这被否决了......事实:XmlSerializer 要求集合属性的设置器。这不是意见,等等 - 试试看...
      【解决方案3】:

      我更喜欢

      public IList<Customer> Customers { get; private set; }
      

      但这需要

      this.Customers = new List<Customer>();
      

      Company构造函数中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-20
        • 2014-12-14
        • 2013-07-16
        • 1970-01-01
        • 2018-05-08
        • 2020-08-06
        • 2012-12-02
        相关资源
        最近更新 更多