궁금한 점이 있으면 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);
}
UPDATE : 내가 허용 대답과 같은 개념 인 마틴 파울러의 책 이름을 "리팩토링"을 읽고 있었다 때이 링크 Encapsulate collection을 발견
.
예 2 "개인 목록 colPhones;" 사용하지 않은 것처럼 보입니다. 이전에 프로그램을 다시 작성한 결과물입니까? –
RenniePet
사용해야합니다. 'Phones' getter 안에'this.Phones' 대신'this.colPholes'를 참조해야합니다. 그렇지 않으면 속성에 액세스 할 때마다 StackOverflowExceptions를 계속 throw하는 순환 참조를 얻게됩니다. – krillgar