【问题标题】:How to overload for return types [duplicate]如何重载返回类型[重复]
【发布时间】:2012-10-22 22:12:04
【问题描述】:

可能重复:
Really impossible to use return type overloading?

有没有办法采用相同的方法并重载其返回类型?就像我在下面的代码中所做的那样。我试过这个,但它说两者之间有歧义。

//supporting methods
private AutoResetEvent ReturnData = new AutoResetEvent(false);
public void PostMessage(string msg)
{ this.Message = msg; this.ReturnData.Set(); }
private string Message;
//a return value overload
public string GetMessage()
{
    this.ReturnData.WaitOne();
    return this.Message;
}
public byte[] GetMessage(){
    this.ReturnData.WaitOne();
    return encoder.GetBytes(Message);
}

【问题讨论】:

  • 没有......
  • 不,只是稍微重命名它们,例如GetMessageString 等
  • 恐怕这不可能。

标签: c# .net


【解决方案1】:

在 C# 中不能通过返回类型重载。

当需要在 .NET 框架中完成类似的事情时,他们通常会更改方法名称以包含返回类型的名称。

示例:BinaryReader

double ReadDouble() { ... }
int ReadInt32() { ... }

示例:SQLDataReader

double GetDouble(int i) { ... }
int GetInt32(int i) { ... }
etc...

在您的情况下,您可以例如使用GetMessageStringGetMessageBytes

【讨论】:

    【解决方案2】:

    这是C# language specification 1.6.6 节的摘录:

    "方法的签名在声明该方法的类中必须是唯一的。方法的签名由方法的名称、类型参数的个数以及它的个数、修饰符和类型组成参数。方法的签名不包括返回类型。"

    【讨论】:

      【解决方案3】:

      重载解析适用于方法签名。

      方法签名由方法名称和参数类型和编号组成,但不包括返回类型。

      这意味着您不能仅通过返回类型重载方法。

      在这种情况下,最好根据返回类型来命名方法。

      【讨论】:

        【解决方案4】:

        不,你不能,签名不依赖于返回类型,所以解决方案可能是:

        public string GetMessageString()
        {
            this.ReturnData.WaitOne();
            return this.Message;
        }
        public byte[] GetMessageBytes(){
            this.ReturnData.WaitOne();
            return encoder.GetBytes(Message);
        }
        

        或者您可以使用泛型类型来解决问题:

        public T GetMessage<T>()
        {
            this.ReturnData.WaitOne();
            if(typeof(T) == typeof(string))
               return this.Message;
            else if(typeof(T) == typeof(byte[]))
               return encoder.GetBytes(Message);
        
            return default(T);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-09-06
          • 2012-03-23
          • 1970-01-01
          相关资源
          最近更新 更多