DCSIMG
Collection Initializers for custom object - שלמה גולדברג (הרב דוטנט)

שלמה גולדברג (הרב דוטנט)

מרצה בסלע ויועץ בעולם ה - net.

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()

};

פורסם: May 12 2011, 11:27 AM by Shlomo | with no comments
תגים:,
שלח תגובה

(שדה חובה)  

(שדה חובה)  

(אופציונלי)

(שדה חובה) 

Please add 4 and 6 and type the answer here:


Enter the numbers above: