我有一个类Locale,它包含一个名为Values的公共字典 我想要的是:
Locale l = new Locale(.....);
// execute stuff that loads the Values dictionary...
// currently to get the values in it I have to write :
string value = l.Values["TheKey"];
// What I want is to be able to get the same thing using :
string value = l["TheKey"];
当使用方括号和自定义类时,我基本上想要更改返回值。
答案 0 :(得分:1)
如评论中所述,您可以为班级indexer
实施Locale
。
实施例
public class Locale
{
Dictionary<string, string> _dict;
public Locale()
{
_dict = new Dictionary<string, string>();
_dict.Add("dot", "net");
_dict.Add("java", "script");
}
public string this[string key] //this is the indexer
{
get
{
return _dict[key];
}
set //remove setter if you do not need
{
_dict[key] = value;
}
}
}
用法:
var l = new Locale();
var value = l["java"]; //"script"
以下是MSDN参考。