번역/C# Notes for Professionals
26.3: 사용자 정의 class 를 컬렉션 초기자 (Collection initializer) 로 초기화하기
노초코
2021. 7. 8. 14:50
Section 26.3: 사용자 정의 class 를 컬렉션 초기자 (Collection initializer) 로 초기화하기
특정 class 가 컬렉션 초기자 (Collection initializer) 를 지원하기 위해서는, 해당 class 가 IEnumerable
인터페이스를 상속받아야 하며, 또한 최소한 하나의 Add
메소드를 가져야 한다. C# 6 부터는, extension method 를 사용하여 IEnumerable
을 상속받는 어떠한 collection 일지라도 사용자가 정의한 Add
메소드를 추가해줄 수 수 있다.
class Program {
static void Main() {
var col = new MyCollection {
"foo",
{
"bar",
3
},
"baz",
123.45 d,
};
}
}
class MyCollection: IEnumerable {
private IList list = new ArrayList();
public void Add(string item) {
list.Add(item)
}
public void Add(string item, int count) {
for (int i = 0; i < count; i++) {
list.Add(item);
}
}
public IEnumerator GetEnumerator() {
return list.GetEnumerator();
}
}
static class MyCollectionExtensions {
public static void Add(this MyCollection @this, double value) =>
@this.Add(value.ToString());
}
본 문서는 C# Notes for Professionals (라이센스:CC-BY-SA) 를 한글로 번역한 문서입니다. 번역상 오류가 있을 수 있으므로 정확한 내용은 원본 문서를 참고하세요.
[출처] https://books.goalkicker.com/CSharpBook/
반응형