可能重复:
如何在 C# 中重载方括号运算符?
对于一个类,是否可以在 C# 中重载运算符 []?
如果是这样,声明 [] 重载函数的正确语法是什么?
运算符 [] 也可以根据给定的参数返回不同的数据类型吗?如果不是,您认为我的其他解决方案是什么?我应该改用 Object 吗?
public class MyClass {
private Dictionary<string,Element> eAttribs;
private Dictionary<string,string> defAttribs;
// Also can the operator [] returns different data types based off the parameter given?
// If not, what do you think is my other solution?
public Element operator[](string attribKey) {
if (eAttribs.containsKey(attribKey)
return eAttribs[attribKey];
else return null;
}
// COMPILE Error below: Unexpected symbol '['
public string operator[](string attribKey) {
if (defAttribs.containsKey(attribKey)
return defAttribs[attribKey];
else return null;
}
}