索引器
它使对象能像数组一样,即使用下标,进行索引
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);
}
}
}
}
}