Collection Initializers for custom object
אחד הפיצ'רים הנחמדים שנכנסו ב - C# 3.0 הוא Collection Initializers.
עד C# 3.0 יכולנו לכתוב קוד כזה:
int[] arr = new int[] { 1, 2, 3, 34 };
מ - C# 3.0 אפשר גם לכתוב עבור Collections
List<int> list = new List<int>() { 1, 2, 3, 34 };
Dictionary<string, int> dic = new Dictionary<string, int>()
{
{"a", 1},
{"b", 2},
{"c", 3},
{"d", 4},
};
שזה באמת נחמד.
אבל יש דבר נוסף שטוב להכיר,
מסתבר שכל אובייקט שמממש את ICollection<T או שמממש את
IEnumerable ויש לו מתודה בשם Add אפשר להשתמש בטריק הזה, לדוגמא:
class Person { }
class PersonManager : IEnumerable
{
public void Add(Person item)
{
}
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
PersonManager manager = new PersonManager()
{
new Person(),
new Person(),
new Person()
};