索引器-使用字符串做数组索引

索引器-使用字符串做数组索引

使用字符串做数组索引,方便识别。

参见《C#图解教程(第4版)》第6章深入理解类,第6.17节索引器P107。

索引器是一组get和set访问器,与属性类似。

声明索引器语法注意:

  • 索引器没有名称,在名称的位置是关键字this。
  • 参数列表在方括号中间。
  • 参数列表中必须至少声明一个参数。
  1. 示例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";
  1. 示例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");
        };
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值