代码如下
namespace _03_索引器与Dictionary
{
internal class Program
{
static void Main(string[] args)
{
Student stu = new Student();
var mathScore = stu["Math"];
Console.WriteLine(mathScore);
stu["English"] = 99;
var EnglishScore = stu["English"];
Console.WriteLine(EnglishScore);
}
}
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;
}
else
{
this.scoreDictionary.Add(subject, value.Value);
}
}
}
}
}
输出结果
