c# - 真的不可能使用返回类型重载吗?

标签 c# .net

我用两种方法在 MSIL 中制作了一个小 DLL:

float AddNumbers(int, int)
int AddNumbers(int, int)

有些人可能知道,MSIL 允许您创建具有相同参数的方法,只要您具有不同类型的返回类型(即所谓的返回类型重载)。现在,当我尝试在 C# 中使用它时,正如我所期待的那样,它引发了一个错误:

float f = ILasm1.MainClass.AddNumbers(1, 2);

错误是:

The call is ambiguous between the following methods or properties: 'ILasm1.MainClass.AddNumbers(int, int)' and 'ILasm1.MainClass.AddNumbers(int, int)'

难道c#真的不能区分不同的返回类型吗?我知道我无法对仅具有不同返回类型的方法进行编程,但我总是假设它知道如何处理它。

最佳答案

ECMA-334 C# 8.7.3 节

The signature of a method consists of the name of the method and the number, modifiers, and types of its formal parameters. The signature of a method does not include the return type.

您可以使用通用方法:

T AddNumbers<T>(int a, int b)
{
   if (typeof(T) == typeof(int) || typeof(T) == typeof(float))
   {
      return (T)Convert.ChangeType(a + b, typeof(T));
   }

   throw new NotSupportedException();
}

关于c# - 真的不可能使用返回类型重载吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1481137/

相关文章:

c# - 存储不经常更改的信息以在应用程序中使用的最佳方法?

c# - 构造函数不能调用自己c#

c# - 在另一个线程中运行一个异步函数

c# - DateTime.UtcNow 在不同的服务器中给出不同的值

c# - Entity Framework - 存储库检查(大文本)

c# - 不安全的指针操作

javascript - 单击按钮在 GoogleMap 中移动

.net - 选择参数中的 TSQL 计数

c# - LiveCycle PDF 以 XML 形式提交到 .NET Web 服务

c# - 正则表达式模式匹配 : Using only the start and end of a pattern for matching