【发布时间】:2015-03-26 16:59:20
【问题描述】:
只是好奇,我看到了在 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);
}
更新:
我在阅读 Martin Fowler 的名为“重构”的书时发现了此链接 Encapsulate collection,这与公认答案的概念相同。
【问题讨论】:
-
在示例 2“私人列表
colPhones;”中看起来它是未使用的 - 以前重写程序的工件? -
应该使用。 OP 应该引用
this.colPholes,而不是Phonesgetter 中的this.Phones。否则,他们将获得一个循环引用,每当访问该属性时,该引用将不断抛出 StackOverflowExceptions。
标签: c# list collections