2

为什么我不能执行以下操作?

public interface ICommunication
{
    int Send(Dictionary<string, string> d);
    int Send(byte[] b);

    Dictionary<string, string> Receive();
    byte[] Receive(); // Error
}

的signarureReceive()不同,但参数相同。为什么编译器只看参数而不看成员签名?

ICommunication' 已经定义了一个具有相同参数类型的名为 'Receive' 的成员。

我怎么能解决这个问题?

我可以重命名Receive()如下,但我更愿意将其命名为Receive().

public interface ICommunication
{
    int Send(Dictionary<string, string> d);
    int Send(byte[] b);

    Dictionary<string, string> ReceiveDictionary();
    byte[] ReceiveBytes(); 
}
4

3 回答 3

6

返回类型不是方法签名的一部分,因此从语言的角度来看,接口声明了两次相同的方法。

来自微软的 C# 编程指南

出于方法重载的目的,方法的返回类型不是方法签名的一部分。但是,在确定委托与其指向的方法之间的兼容性时,它是方法签名的一部分。

于 2013-10-11T10:55:13.060 回答
3

如果您决定编写以下代码怎么办:

var x = Receive();

它应该使用什么方法?返回类型是什么?

于 2013-10-11T10:40:16.603 回答
1

在 C# 中是不允许的,因为当您调用它时,Receive()系统如何知道要调用哪个方法?

调用返回字典或字节数组?

所以设计师让它不被支持

例如:var returnVal = ICommunication.Receive()

编辑:

public interface ICommunication
{
    int Send(Dictionary<string, string> d);
    int Send(byte[] b);

   void Receive(out Dictionary<string, string>);
   void Receive(out byte[]); 
}
于 2013-10-11T10:39:28.653 回答