gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:30:10 26 4
gpt4 key购买 nike

我用两种方法在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com