[英]Implementing indexing “operator” in on a class in C#
go 如何在 C# 中的 class 上实现索引“运算符”?
class Foo {
}
Foo f = new Foo();
f["key"] = "some val";
f["other key"] = "some other val";
在 C# 中? 搜索了 MSDN,但空无一物。
这是一个使用字典作为存储的示例:
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;
}
}
}
private List<string> MyList = new List<string>();
public string this[int i]
{
get
{
return MyList[i];
}
set
{
MyList[i] = value;
}
}
如果需要,您可以为不同类型定义多个访问器(例如,字符串而不是 int)。
有称为索引器或有时索引器属性。
这是关于它们的MSDN页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.