1

可能重复:
如何在 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;
     }
}
4

3 回答 3

3

在 c# 中,这些称为索引器。

句法:

public object this[int key]
{
    get
    {
        return GetValue(key);
    }
    set
    {
        SetValue(key,value);
    }
}

您只能返回一个对象。对必须返回的所有类型对象使用基类。

于 2012-06-25T09:06:59.737 回答
2
于 2012-06-25T09:06:21.560 回答
1
于 2012-06-25T09:08:26.363 回答