问题描述
如果我有一个lambda如()=> {抛出新的异常(); }
,目前还不清楚它是否有一个返回类型或没有。正因为如此,它可以是(隐含的)转换为两个动作
和 Func键<对象>
(或任何其他 Func键< T>
)。这是因为,根据§6.5的匿名函数转换的C#的4规范的:
If I have a lambda such as () => { throw new Exception(); }
, it's unclear whether it has a return type or not. Because of this, it can be (implicitly) converted to both Action
and Func<object>
(or any other Func<T>
). This is because, according to §6.5 Anonymous function conversions of the C# 4 spec:
[A]委托键入 D
是一个匿名函数兼容˚F
规定:
-
...
…
如果 D
有一个无效
返回类型和˚F
体是一个语句块中,当[...] ˚F是一个有效的语句块中没有return语句指定一个表达式。
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.
如果 D
具有非void返回类型和 F中的身体
是一个语句块,当[...] ˚F是与非到达终点,其中每个收益
语句指定隐式转换为<$的返回类型的表达式一个有效的语句块C $ C> D 。
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
.
但如果我有一个方法,其中一个有型动作
和其他 Func键℃的参数的两个重载;对象>
,我通过它从上面的拉姆达,在 Func键<对象>
超负荷使用。为什么?规范的哪一部分说, Func键<对象>
比动作
在这种情况下,更好地
But if I have two overloads of a method, where one has a parameter of type Action
and the other Func<object>
, and I pass it the lambda from above, the Func<object>
overload is used. Why? Which part of specification says that Func<object>
is better than Action
in this case?
我已经看过§7.5.3.2的更好的函数成员的,但这并不能解释它。
I have looked at §7.5.3.2 Better function member, but that does not explain it.
推荐答案
我已经看了一款低:§7.5.3.3的从表现更好的转换的解释说:
I should've looked one section lower: §7.5.3.3 Better conversion from expression explains that:
给定一个隐式转换 C
,从一个表达式转换电子
到类型 T
和隐式转换 C
,从一个表达式转换电子
来一个类型 T
, C
比更好转成c
如果以下至少一人持有:
-
...
…
电子
是一个匿名函数, T
是一个委托类型 D
或表达式目录树类型表达式来; d >
, T
是一个委托类型 D
或表达式目录树类型表达式来; d >
和下列情况之一成立:
E
is an anonymous function, T
is either a delegate type D
or an expression tree type Expression<D>
, T
is either a delegate type D
or an expression tree type Expression<D>
and one of the following holds:
-
...
…
D
和 D
具有相同的参数列表,以及以下情况之一成立:
D
and D
have identical parameter lists, and one of the following holds:
-
...
…
D
有一个返回类型是
和 D
是无效的返回
这篇关于LAMBDA转换没有明确的返回类型和重载解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!