索引器-使用字符串做数组索引
使用字符串做数组索引,方便识别。
参见《C#图解教程(第4版)》第6章深入理解类,第6.17节索引器P107。
索引器是一组get和set访问器,与属性类似。
声明索引器语法注意:
- 索引器没有名称,在名称的位置是关键字this。
- 参数列表在方括号中间。
- 参数列表中必须至少声明一个参数。
- 示例1
public class User
{
//声名数组
public string[] val = { "ID", "UserName", "Pass" };
public string[] user = { "20020", "Lilei", "123456" };
//声名索引器
public string this[string index]
{
get { return user[Array.IndexOf(val, index)]; }
set { user[Array.IndexOf(val, index)] = value; }
}
}
//使用
private User user = new User();
user["UserName"] = "Hello";
- 示例2
public string UserName { get; set; }
public string ID { get; set; }
public string Pass { get; set; }
public string this[string index]
{
get
{
switch (index)
{
case "UserName":
return UserName;
case "ID":
return ID;
case "Pass":
return Pass;
default:
throw new Exception("index error");
};
}
set
{
switch (index)
{
case "UserName":
UserName = value;
break;
case "ID":
ID = value;
break;
case "Pass":
Pass = value;
break;
default:
throw new Exception("index error");
};
}
}