如果我有一个lambda,如()=> {throw new Exception(); },不清楚它是否具有返回类型.因此,它可以(隐式地)转换为Action和Func< object> (或任何其他Func T).这是因为,根据§6.5C#4规范的匿名函数转换:
[A] delegate type
D
is compatible with an anonymous functionF
provided:
…
If
D
has avoid
return type and the body ofF
is a statement block,when […] the body ofF
is a valid statement block in which no return statement specifies an expression.If
D
has a non-void return type and the body ofF
is a statement block,when […] the body ofF
is a valid statement block with a non-reachable end point in which eachreturn
statement specifies an expression that is implicitly convertible to the return type ofD
.
但是如果我有一个方法的两个重载,其中一个具有Action类型的参数和另一个Func< object>,并且我从上面传递了lambda,那么Func< object>使用过载.为什么?规范的哪一部分说Func< object>在这种情况下比行动好吗?
我看过§7.5.3.2更好的功能成员,但这并没有解释.
解决方法
Given an implicit conversion
C1
that converts from an expressionE
to a typeT1
,and an implicit conversionC2
that converts from an expressionE
to a typeT2
,C1
is a better conversion thanC2
if at least one of the following holds:
…
E
is an anonymous function,T1
is either a delegate typeD1
or an expression tree typeExpression<D1>
,T2
is either a delegate typeD2
or an expression tree typeExpression<D2>
and one of the following holds:
…
D1
andD2
have identical parameter lists,and one of the following holds:
…
D1
has a return typeY
,andD2
is void returning