更改自定义类方括号返回值

时间:2015-11-07 13:14:52

标签: c# class dictionary brackets square

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

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

1 个答案:

答案 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参考。