c# – 具有不清楚返回类型和重载分辨率的Lambda转换

前端之家收集整理的这篇文章主要介绍了c# – 具有不清楚返回类型和重载分辨率的Lambda转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Peculiar overload resolution with while (true)1
如果我有一个lambda,如()=> {throw new Exception(); },不清楚它是否具有返回类型.因此,它可以(隐式地)转换为Action和Func< object> (或任何其他Func T).这是因为,根据§6.5C#4规范的匿名函数转换:

[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>在这种情况下比行动好吗?

我看过§7.5.3.2更好的功能成员,但这并没有解释.

解决方法

我应该看下面的一个部分:§7.5.3.3从表达式更好的转换解释:

Given an implicit conversion C1 that converts from an expression E to a type T1,and an implicit conversion C2 that converts from an expression E to a type T2,C1 is a better conversion than C2 if at least one of the following holds:

  • E is an anonymous function,T1 is either a delegate type D1 or an expression tree type Expression<D1>,T2 is either a delegate type D2 or an expression tree type Expression<D2> and one of the following holds:

    • D1 and D2 have identical parameter lists,and one of the following holds:

      • D1 has a return type Y,and D2 is void returning

猜你在找的C#相关文章