1

Values という名前のパブリック ディクショナリを含むクラス Locale があります。
私が欲しいのは:

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クラスに を実装できます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 に答える