问题描述
将方法分配给 Func
-type 时,我收到编译错误 无法确定条件表达式的类型,因为方法组"和方法组"之间没有隐式转换'代码>.
When assigning a method to a Func
-type, I get the compilation error Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'
.
这只发生在 上?:
运算符.代码:
This only happens with the ? :
operator. The code:
public class Test
{
public static string One(int value)
{
value += 1;
return value.ToString();
}
public static string Two(int value)
{
value += 2;
return value.ToString();
}
public void Testing(bool which)
{
// This works
Func<int, string> actionWorks;
if (which) actionWorks = One; else actionWorks = Two;
// Compilation error on the part "One : Two"
Func<int, string> action = which ? One : Two;
}
}
我发现 一些关于协变和逆变的信息,但我不明白这如何适用于上述情况.为什么这不起作用?
I found some information about co- and contravariance, but I don't see how that applies to the situation above. Why doesn't this work?
推荐答案
您需要显式提供至少一个方法组的签名.但是,在这样做之后,编译器将允许您将 action
声明为隐式类型的本地:
You need to explicitly provide the signature of at least one method group. However, after doing it the compiler will allow you to declare action
as an implicitly-typed local:
var action = which ? (Func<int, string>)One : Two;
发生这种情况的原因是 operator ?:
的返回类型不是根据您尝试分配给它的内容推导出来的,而是根据两个表达式的类型推导出来的.如果类型相同或者它们之间存在隐式转换,则编译器推导出返回类型成功;否则,它会抱怨没有转换.
The reason this happens is that the return type of operator ?:
is not deduced based on what you are trying to assign it to, but based on the types of the two expressions. If the types are the same or there is an implicit conversion between them, the compiler deduces the return type successfully; otherwise, it complains that there is no conversion.
这篇关于无法确定条件表达式的类型 (Func)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!