c# - 带有函数参数的重载函数的奇怪模糊调用

标签 c# function-pointers

<分区>

假设我有一个重载的方法。一种采用返回 uint 的函数,一种采用返回 int 的函数。

static void test1(Func<uint> f)
{
    //things
}
static void test1(Func<int> f)
{
    // also things
}

现在我试着这样调用它:

test1(Random.FunctionThatReturnsUints);

但是我在编译时得到了一个不明确的调用错误:

   Error    4   The call is ambiguous between the following methods or
    properties: 'RNG_Comparison.Run.test1(System.Func<int>)' and 'RNG_Comparison.Run.test1
(System.Func<uint>)'

这是怎么回事?重载一个函数的全部意义不是让它根据类型隐含地理解你的意思吗?我的意思是,如果我用返回 BigInt 或其他东西的 func 调用它,也许我可以看到编译器的困惑,但这个看起来很简单。

有谁知道我为什么会收到这个错误?

最佳答案

重要的是post by Eric Lippert Tim 引用的是:

The principle here is that determining method group convertibility requires selecting a method from a method group using overload resolution, and overload resolution does not consider return types.

在您的代码中有方法组转换在起作用,这导致了问题。 提议的解决方案消除了这个问题。

关于c# - 带有函数参数的重载函数的奇怪模糊调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19031565/

相关文章:

c++ - 如何检查函数指针是否存在

c++ - 为什么stateless functor的operator()不能是static的?

c# - 部分 View 忽略数据集且不显示

c# - ODBC 连接问题 : Function Sequence error when executing anything

回调函数误解

c++ - 在 C 中,将函数指针赋值给适当类型的变量给出 "cannot convert ... in assignment"

c++ - 在运行时定义 C++ 函数

c# - 如何从一个类的多个属性生成一个数组

c# - 分离数百个事件处理程序

c# - 在 C# 运行时创建自定义对象