自定义按照index和key访问的List

  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"];
     }
}

 

  以上方法中添加了一个按照名称的索引器,这样访问起来就方便了!

posted @ 2014-03-20 11:31  One Day  阅读(339)  评论(0编辑  收藏  举报