1

我有一个类 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"];

当使用方括号和自定义类时,我基本上想更改返回值。

4

1 回答 1

2

如评论中所述,您可以indexer为您的 class实现一个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参考。

于 2015-11-07T13:32:00.360 回答