一、索引器("ind"+Tab*2)
//主函数
try
{
Student stu = new Student();
stu["Math"] = 200;
stu["Math"] = 300;
var mathScore = stu["Math"];
Console.WriteLine(mathScore);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message );
}
//类的声明
class Student
{
private Dictionary<string, int> scoreDictionary = new Dictionary<string, int>();
public int? this[string subject]
{
get {
if (scoreDictionary.ContainsKey (subject ))
{
return this.scoreDictionary[subject];
}
else
{
return null;
}
}
set {
if (value.HasValue ==false)
{
throw new Exception("Score cannot be null.");
}
if (scoreDictionary.ContainsKey (subject))
{
this.scoreDictionary[subject] = value.Value;
}
else
{
scoreDictionary.Add(subject, value.Value);
}
}
}
}
二、常量(属于类,const)(类的声明类和结构不可以被声明为常量)
//主函数
Console.WriteLine(Student.Amount);
//类的声明
class Student
{
public const int Amount=60;
}