如何在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)
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)定义多个访问器.