您可以将索引器应用于您的课程。
推荐使用,因为它改进了封装。例如,完全有可能使用原始代码将 Dictionary 完全替换为不同的字典——这可能是不可取的。
public class MyClass
{
// Note that dictionary is now private.
private Dictionary<Beep, String> Stuff { get; set; }
public String this[Beep beep]
{
get
{
// This indexer is very simple, and just returns or sets
// the corresponding element from the internal dictionary.
return this.Stuff[beep];
}
set
{
this.Stuff[beep] = value;
}
}
// Note that you might want Add and Remove methods as well - depends on
// how you want to use the class. Will client-code add and remove elements,
// or will they be, e.g., pulled from a database?
}
用法:
MyClass myClass = new MyClass();
string myValue = myClass[Beep.LetsGo];