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

2018-06-17 20:54:48来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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

 

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

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Web 开发人员需知的 Web 缓存知识

下一篇:嵌套repeater