索引器(概述)
- 什么是索引器
- 索引器(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);
}
}
}
}