c# - 返回类型和重载解析不明确的 Lambda 转换

标签 c# lambda overload-resolution

<分区>

如果我有一个 lambda,例如 () => { throw new Exception(); } ,不清楚它是否有返回类型。因此,它可以(隐式)转换为 Action。和 Func<object> (或任何其他 Func<T> )。这是因为,根据 C# 4 规范的 §6.5 匿名函数转换:

[A] delegate type D is compatible with an anonymous function F provided:

  • If D has a void return type and the body of F is a statement block, when […] the body of F is a valid statement block in which no return statement specifies an expression.

  • If D has a non-void return type and the body of F is a statement block, when […] the body of F is a valid statement block with a non-reachable end point in which each return statement specifies an expression that is implicitly convertible to the return type of D.

但是如果我有一个方法的两个重载,其中一个有一个类型为 Action 的参数和另一个Func<object> ,然后我从上方将 lambda 传递给它,Func<object>使用过载。为什么?规范的哪一部分说 Func<object>优于Action在这种情况下?

我看过 §7.5.3.2 更好的函数成员,但这并不能解释它。

最佳答案

我应该往下看一节:§7.5.3.3 更好地从表达式转换 解释说:

Given an implicit conversion C<sub>1</sub> that converts from an expression E to a type T<sub>1</sub>, and an implicit conversion C<sub>2</sub> that converts from an expression E to a type T<sub>2</sub>, C<sub>1</sub> is a better conversion than C<sub>2</sub> if at least one of the following holds:

  • E is an anonymous function, T<sub>1</sub> is either a delegate type D<sub>1</sub> or an expression tree type Expression<D<sub>1</sub>>, T<sub>2</sub> is either a delegate type D<sub>2</sub> or an expression tree type Expression<D<sub>2</sub>> and one of the following holds:

    • D<sub>1</sub> and D<sub>2</sub> have identical parameter lists, and one of the following holds:

      • D<sub>1</sub> has a return type Y, and D<sub>2</sub> is void returning

关于c# - 返回类型和重载解析不明确的 Lambda 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11941779/

相关文章:

c# - 父命名空间中的类可以访问子命名空间中的类

c# - 如何使用C#在IIS Express中创建虚拟目录

c++ - 涉及模板化转换运算符和隐式复制构造函数的歧义

c++ - 在函数声明末尾重载 “const”

c# - T 泛型不适用于构建器模式

c# - XAML 中带有黑色边框的白色字体

c++ - 如何从 C++14 中的广义 lambda 捕获返回包含 std::unique_ptr 的 std::function ?

c++ - 在 C++ 中将匿名函数分配给函数指针方法

c++ - Lambda 函数无法调用函数模板参数的静态函数

c++ - 在此示例中,赋值运算符重载决策如何工作?结果出乎我的意料