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 = ; 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 = };
persons.Add(new Person(){Name = "Han Meimei", Age = }; Person HanMeimei = persons["Han Meimei"];
}
}
以上方法中添加了一个按照名称的索引器,这样访问起来就方便了!