首页 > 学院 > 开发设计 > 正文

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

2019-11-14 16:47:34
字体:
来源:转载
供稿:网友

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

 

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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表