using System;
using System.Collections.Generic;
namespace ConsoleIdeaTest
{
internal class Program
{
static void Main(string[] args)
{
var stu1 = new Student();
stu1["math"] = 90;
var mathScore = stu1["math"];
Console.WriteLine(mathScore);
}
}
class Student
{
private Dictionary<string, int> scoreDictionary = new Dictionary<string, int>(); //创建字典,k--subject,v--value
public int? this[string subject] //创建索引器,查找的内容是subject
{
get
{
if(this.scoreDictionary.ContainsKey(subject)) //在字典中查找是否有该subject
return scoreDictionary[subject]; //如果在字典中找到了该subject,则返回字典中subject对应的值
else
return null; //如果在字典中找不到该subject,则get返回null
}
set
{
if (value.HasValue == false) //如果输入的分数为空,则抛出
{
throw new Exception("Score can not be null."); //如果输入的分数为空,则抛出
}
if (this.scoreDictionary.ContainsKey(subject)) //如果在字典中能找到该subject
{ this.scoreDictionary[subject] = value.Value; } //则返回该subject对应的分数值
else
{ this.scoreDictionary.Add(subject, value.Value);} //如果在字典中找不到该subject,则添加该subject和对应的分数值
}
}
}
}
C# 非集合方式举例说明索引器的声明和使用。
上述代码示范了索引器的创建和索引器的作用方法。该示例特意选取了非集合的情况下来用索引器。