【问题标题】:Overload [] operator in C# and give more than one return value [duplicate]在C#中重载[]运算符并给出多个返回值[重复]
【发布时间】:2012-06-26 12:40:10
【问题描述】:

可能重复:
How do I overload the square-bracket operator in 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;
     }
}

【问题讨论】:

  • 您可以通过将参数计数与索引器不同来模拟它。见我的回答和最后的演示。

标签: c# operator-overloading


【解决方案1】:

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

语法:

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

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

【讨论】:

    【解决方案2】:

    对于一个类,是否可以在 C# 中重载运算符 []?

    是的。语法是重载this[]属性(“indexer”):

    public Element this[string attribKey] {
        get { … }
        set { … }
    }
    

    运算符 [] 也可以根据给定的参数返回不同的数据类型吗?

    不,很遗憾没有。 C# 一般禁止基于返回类型的重载解析;它只考虑参数类型。

    【讨论】:

      【解决方案3】:

      您可以返回对象或使用dynamic Type

      public dynamic this[string key]
      {
           get 
           {
               //return value;
           }
           set
           {
               //set value; 
           }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-04-26
        • 1970-01-01
        • 2015-01-02
        • 2013-11-08
        • 1970-01-01
        • 2013-07-31
        • 1970-01-01
        • 1970-01-01
        • 2015-08-12
        相关资源
        最近更新 更多