C#学习笔记 索引器

索引器(概述)

  • 什么是索引器
    • 索引器(indexer)是这样一种成员:它使对象能够用与数组相同的方式(即使用下标)进行索引
  • 索引器的声明
    • 参见C#语言定义文档
    • 注意:没有静态索引器

1.索引器通常用于集合类型(下例代码的非集合类型情况很少见);
2.平时对于初学者很少有机会写索引器。

    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            stu["Math"] = 90;
            stu["Math"] = 100;
            var mathScore = stu["Math"];
            Console.WriteLine(mathScore);
        }
    }
    class Student
    {
        private Dictionary<string, int> scoreDictionary = new Dictionary<string, int>();

        public int? this[string subject]
        {
            get 
            {
                if (this.scoreDictionary.ContainsKey(subject))
                {//首先判断字典里是不是包含了这个Key(subject),有的话用subject索引字典,把拿到的值返还回去
                    return this.scoreDictionary[subject];
                }
                else
                {//没有的话就返回null
                    return null;
                }
            }
            set 
            {
                if (value.HasValue==false)
                {//如果传入的值为null,或者没有传值进来
                    throw new Exception("Score cannot be null.");
                }
                if (this.scoreDictionary.ContainsKey(subject))
                {//首先判断字典里是不是包含了这个subject,如果已经包含了,就更新这个值
                    this.scoreDictionary[subject] = value.Value;
                    //与属性一样,这里也会有C#提供的value变量
                }
                else
                {
                    this.scoreDictionary.Add(subject, value.Value);
                }
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值