向集合添加元素的方法

时间:2015-01-27 22:35:06

标签: c# list collections

只是好奇,我看到了两种在C#中创建集合的方法。对我而言,它只是一种风格,但也许还有另一种解释。性能?这是否符合模式?在示例2中我唯一能看到的是,它是一种防止覆盖集合的方法。

示例1:

public class Employee
{
   ...
   public List<Phone> Phones
   {
      get; set;
   }
   ...
}

因此。来自另一个班级

Employee employee = new Employee();
employee.Phones = this.GetPhones();

示例2:

public class Employee
{
   ...
   private List<Phone> colPhones;
   public List<Phone> Phones
   {
      get
      {
         if(this.Phones == null)
         {
             this.Phones = new List<Phone>();
         }
         return this.Phones;
      }
   }
   ...
   public void AddPhone(Phone phone)
   {
       this.Phones.Add(phone);
   }
}

所以

Employee employee = new Employee();
List<Phone> phones = this.GetPhones();
//--> Here, I know I can use for(int i....) instead of foreach. This is just for the example.
foreach(Phone phone in phones) 
{
   employee.Phones.Add(phone);
}

更新

当我读到一本名为&#34;重构&#34;的马丁福勒的书时,我找到了这个链接Encapsulate collection。这与接受的答案是相同的概念。

2 个答案:

答案 0 :(得分:1)

执行以下代码时,私有成员变量将在代码的IL级别中创建。

public List<Phone> Phones { get; set; }

第二种方法是实现延迟加载的一种方法。通常,不提供this.Phones = new List<Phone>();,而是提供一种从数据库生成集合的方法。使用第二种方案的另一个原因是不要覆盖任何现有的集合,但避免在引用属性时担心NullReferenceException

对于95%的情况,第一种情况没问题。

在这两个示例中,没有什么能阻止Employee类的使用者执行以下操作:employee.Phones.Add(new Phone())。除非您创建属性readonly,否则无法阻止修改集合,但是您只能在Employee类的构造函数中设置它,然后您的AddPhone()方法将会变得无法使用。

答案 1 :(得分:1)

在我看来,你的第一个例子是相当危险的。你自己说它很容易被覆盖&#34;该集合,但我认为更重要的是,如果你不是非常小心,它很容易对集合进行微妙的修改。

Employee employee = new Employee();
List<Phone> obscureTemporaryVariable = this.GetPhones();
employee.Phones = obscureTemporaryVariable;
...
// much later, after having forgotten all about the above bit of code
obscureTemporaryVariable.Clear();
obscureTemporaryVariable.Add(new Phone(42));

现在,您(大概是无意中)修改了&#34;员工&#34;的电话号码。

相关问题