18. Collection Initializer

בC# 3.0 הוסיפו Feature נחמד של syntatic sugar בשפה בכדי לאתחל Collectionים

נניח שיש לנו class פשוט, למשל

1
2
3
4
5
6
7
8
9
10
11
12
public class Person
{
public string Name
{
get; set;
}
public int Age
{
get; set;
}
}

יהי IEnumerable שיש לו פונקציית Add, למשל

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class PersonCollection : IEnumerable<Person>
{
private ICollection<Person> m_PersonCollection = new List<Person>();
public void Add(string name, int age)
{
Person person = new Person();
person.Name = name;
person.Age = age;
m_PersonCollection.Add(person);
}
#region IEnumerable<Person> Members
// ...
#endregion
}

אז במקום לאתחל אותו כך:

1
2
3
4
5
6
7
8
PersonCollection people = new PersonCollection();
people.Add("John", 48);
people.Add("Hurley", 32);
people.Add("James", 39);
people.Add("Sayid", 40);
people.Add("Jack", 37);
people.Add("Jin", 33);

נוכל לאתחל אותו עם הsyntax הנחמד הבא:

1
2
3
4
5
6
7
8
9
10
PersonCollection people =
new PersonCollection
{
{"John", 48},
{"Hurley", 32},
{"James", 39},
{"Sayid", 40},
{"Jack", 37},
{"Jin", 33}
};

מה שקורה זה שמתבצעת פנייה לפונקציית הAdd שהמחלקה חושפת, ומתבצע בעצם הקוד שרשמנו למעלה.

אם רוצים להוסיף פרמטר, פשוט צריך לשנות את פונקציית הAdd.

בנוסף ניתן "להחביא" את הType של המחלקה ולהשתמש בממשק במקום בצורה הזאת, ע"י

1
2
3
4
5
6
7
8
9
10
IEnumerable<Person> people =
new PersonCollection
{
{"John", 48},
{"Hurley", 32},
{"James", 39},
{"Sayid", 40},
{"Jack", 37},
{"Jin", 33}
};

שימושים:

IDictionary<TKey, TValue> מממש את הממשק IEnumerable<KeyValuePair<TKey, TValue>> כפי שראינו אתמול.

בנוסף יש לו פונקציית public void Add(TKey key, TValue value) ולכן נוכל לאתחל אותו כך:

1
2
3
4
5
6
7
IDictionary<int, string> idToName =
new Dictionary<int, string>
{
{123456789, "Israel Israeli"},
{314159265, "Apple Pi"},
{011235813, "Fibbo Nacci"},
};

במקום כך:

1
2
3
4
5
6
IDictionary<int, string> idToName =
new Dictionary<int, string>();
idToName.Add(123456789, "Israel Israeli");
idToName.Add(314159265, "Apple Pi");
idToName.Add(011235813, "Fibbo Nacci");

הערה: החל מC# 6.0, הסינטקס הזה עובד גם על Extension Method בשם Add.

יום טוב

שתף