在C#中的类中实现索引“operator”
如何在C#中的类上实现索引“运算符”?
class Foo { } Foo f = new Foo(); f["key"] = "some val"; f["other key"] = "some other val";
在C#? 搜索过MSDN,但空洞了。
以下是使用字典作为存储的示例:
public class Foo { private Dictionary _items; public Foo() { _items = new Dictionary(); } public string this[string key] { get { return _items[key]; } set { _items[key]=value; } } }
private List MyList = new List (); public string this[int i] { get { return MyList[i]; } set { MyList[i] = value; } }
如果需要,您可以为不同类型定义多个访问器(例如,字符串而不是int)。
有人称索引器或有时称索引器属性。
这是关于它们的MSDN页面。