c# 索引器(indexer)

本文介绍了如何在C#中使用`Dictionary`实现类Student的动态索引器,允许通过字符串键获取和设置成绩。实例展示了如何创建索引,设置和访问`scoreDictionary`中的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

索引器

它使对象能像数组一样,即使用下标,进行索引

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            stu["Math"] = 90;
            stu["Math"] = 100;
            var mathScore = stu["Math"];
            //Console.WriteLine(mathScore == null);
            Console.WriteLine(mathScore);
        }
    }

    class Student
    {
        private Dictionary<string, int> scoreDictionary = new Dictionary<string, int>();

		//键入indexer,敲tab键生成框架
        public int? this[string index]
        {
            get
            {
                /* return the specified index here */
                if (this.scoreDictionary.ContainsKey(index))
                {
                    return this.scoreDictionary[index];
                }
                else
                {
                    return null;
                }
            }
            set
            { /* set the specified index to value here */
                // 检验是否为空
                if (value.HasValue == false)
                {
                    throw new Exception("值为空");
                }


                // 判断键是否已经存在,如果已经存在就更新值
                // 因为这里的值是可以为空的(int?),所有要用value.Value来取值
                if (this.scoreDictionary.ContainsKey(index))
                {
                    this.scoreDictionary[index] = value.Value;
                }
                else
                {
                    this.scoreDictionary.Add(index, value.Value);
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值