- 什么是索引器
- 索引器(indexer)是这样一种成员:它使对象能够用与数组相同的方式(即使用下标)进行索引
- 索引器的声明
- 参加 C#语言定义文档
- 注意:没有静态索引器
Code Snippet
index + 2 * TAB:快速声明索引器
索引器一般都是用在集合上面,像如下示例这样用是很少见的(只是为了讲解方便)。
class Program{static void Main(string[] args){Student stu = new Student();stu["Math"] = 90;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)){return this.scoreDictionary[subject];}else{return null;}}set{if (value.HasValue==false){throw new Exception("Score cannot be null.");}if (this.scoreDictionary.ContainsKey(subject)){this.scoreDictionary[subject] = value.Value;//int为可空类型,但是字典里的value不能为可空类型,所以要加“.Value”。}else{this.scoreDictionary.Add(subject, value.Value);}}}}
