List<T>用起來比較方便,但是有時候要按照Index來訪問List中的對象有些繁瑣,所以想是不是擴展一下,既能按照Index來訪問,又能按照Key訪問。
實現方法:
public class Person { public string Name { get; set; } public int Age { get; set; } } public class PersonCollecton : List<Person> { public Person this[string name] { get { for (int i = 0; i < this.Count; i++) { if (this[i].Name == name) return this[i]; } return null; } } } public calss Test { static void Main() { PersonCollection persons = new PersonCollection(); persons.Add(new Person(){Name = "Li Lei", Age = 35}; persons.Add(new Person(){Name = "Han Meimei", Age = 32}; Person HanMeimei = persons["Han Meimei"]; }}
以上方法中添加了一個按照名稱的索引器,這樣訪問起來就方便了!
新聞熱點
疑難解答