C#的索引器和属性差不多,主要是为了让类成员可以像数组一样的查询和使用,不用循环,加快了查询。但是一般的集合都实现了,比如List,Dictionary,ArrayList,数组。
在类中有个集合或数组,你有它成员的ID或关键字,就可以用索引快速的查询。
public class Person
{
private List<Person> li = new List<Person>(); // 存储成员
private Dictionary<string, Person> list = new Dictionary<string, Person>(); // 存储成员
public string Name { get; set; }
public string Height { get; set; }
public string Weight { get; set; }
// 数字索引
public Person this[int index]
{
get
{
return (li[index]);
}
set
{
li.Add(value);
list.Add(value.Name, value);
}
}
// 字符索引
public Person this[string key]
{
get
{
return this.list[key];
}
set
{
this.list[value.Name] = value;
this.li.Add(value);
}
}
public override string ToString()
{
return "我的名字是" + Name + " 身高" + Height + " 体重" + Weight;
}
}
在前台
// 添加成员,也可以用构造函数添加
protected void Page_Load(object sender, EventArgs e)
{
// 添加成员
Person people = new Person();
people[0] = new Person { Name = "士大夫", Height = "152", Weight = "152" };
people[1] = new Person { Name = "他文身断发", Height = "152", Weight = "152" };
people[2] = new Person { Name = "二手单反", Height = "152", Weight = "152" };
people[3] = new Person { Name = "查询", Height = "152", Weight = "152" };
people[4] = new Person { Name = "吊死扶伤啊", Height = "152", Weight = "152" };
people[5] = new Person { Name = "玩儿", Height = "152", Weight = "152" };
people[6] = new Person { Name = "玩儿瑞文", Height = "152", Weight = "152" };
people[7] = new Person { Name = "额问题去", Height = "152", Weight = "152" };
people[8] = new Person { Name = "工本费", Height = "152", Weight = "152" };
people["qq"] = new Person { Name = "qq", Height = "152", Weight = "152" };
// 索引成员
Response.Write(people[3].ToString());
Response.Write(people["玩儿瑞文"].ToString());
Response.Write(people["qq"].ToString());
Response.Write(people[9].ToString());
这样就不必去循环匹配了