索引器的一般写法:

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

        private int this[string subject]
        {
            get { return score[subject]; }
            set{ score[subject] = value; }
        }
    }

 

  

static void Main(string[] args)
        {
            
            MyClass myClass = new MyClass();
            int? mathScore = myClass["Math"];
            mathScore = 50;
            Console.WriteLine(mathScore);
        }


    }

    class MyClass
    {
        Dictionary<string, int> score = new Dictionary<string, int>();

        public int? this[string subject]    //返回值为可空的int类型
        {
            get
            {
                if (score.ContainsKey(subject))    //如果在score中能够查找到subject键
                {
                    return score[subject];
                }
                else
                {
                    return null;
                }
            }
            set
            {
                if (value.HasValue==false)
                {
                    throw new Exception("Score can not be null");
                }

                if (score.ContainsKey(subject))
                {
                    score[subject] = value.Value;
                }
                else
                {
                    score.Add(subject, value.Value);    //如果没有查找到score的键,就在字典中添加键和对应的值
                }
            }
        }
    }

 

posted on 2023-02-15 13:43  漂乎兮乎  阅读(46)  评论(0)    收藏  举报