我只是好奇,发现在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)的书《重构》时,发现了这个链接“封装集合”,这与已接受的答案是相同的概念。
this.colPholes
而不是this.Phones
来引用Phones
getter内部的属性。否则,每当访问该属性时,都会出现循环引用,导致不断抛出StackOverflowExceptions异常。 - krillgar