在C#中的类中实现索引"operator"

thr*_*thr 2 .net c# asp.net

如何在C#中的类上实现索引"运算符"?

class Foo {

}

Foo f = new Foo();
f["key"] = "some val";
f["other key"] = "some other val";
Run Code Online (Sandbox Code Playgroud)

在C#?搜索过MSDN,但空洞了.

Guf*_*ffa 14

以下是使用字典作为存储的示例:

public class Foo {

    private Dictionary<string, string> _items;

    public Foo() {
        _items = new Dictionary<string, string>();
    }

    public string this[string key] {
        get {
            return _items[key];
        }
        set {
            _items[key]=value;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)


Bra*_*ann 5

    private List<string> MyList = new List<string>();
    public string this[int i]
    {
        get
        {
            return MyList[i];
        }
        set
        {
            MyList[i] = value;
        }

    }
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以为不同类型(例如字符串而不是int)定义多个访问器.


Cam*_*and 5

有人称索引器或有时称索引器属性.

这是关于它们的MSDN页面.