C# 非集合方式举例说明索引器的声明和使用

using System;
using System.Collections.Generic;

namespace ConsoleIdeaTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var stu1 = new Student();
            stu1["math"] = 90;
            var mathScore = stu1["math"];
            Console.WriteLine(mathScore);
        }
    }

    class Student
    {
        private Dictionary<string, int> scoreDictionary = new Dictionary<string, int>();  //创建字典,k--subject,v--value
        public int? this[string subject]  //创建索引器,查找的内容是subject
        {
            get 
            {
                if(this.scoreDictionary.ContainsKey(subject))  //在字典中查找是否有该subject
                    return scoreDictionary[subject];  //如果在字典中找到了该subject,则返回字典中subject对应的值
                else
                    return null;  //如果在字典中找不到该subject,则get返回null
            }
            set 
            {
                if (value.HasValue == false)  //如果输入的分数为空,则抛出
                {
                    throw new Exception("Score can not be null.");  //如果输入的分数为空,则抛出
                }
                if (this.scoreDictionary.ContainsKey(subject))  //如果在字典中能找到该subject
                { this.scoreDictionary[subject] = value.Value; }  //则返回该subject对应的分数值
                else
                { this.scoreDictionary.Add(subject, value.Value);}  //如果在字典中找不到该subject,则添加该subject和对应的分数值
            }
        }
    }
}

C# 非集合方式举例说明索引器的声明和使用。

上述代码示范了索引器的创建和索引器的作用方法。该示例特意选取了非集合的情况下来用索引器。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值