我看到过类似的问题,但是它们涉及不同的类型,所以我认为这是一个新问题。
考虑以下代码:
public void Test(bool value)
{
// The following line provokes a compiler error:
// "Type of conditional expression cannot be determined because there is
// no implicit conversion between 'method group' and 'method group".
Func<bool> test = value ? F : F;
}
public bool F()
{
return false;
}
现在,根据 C# 3.0 标准,
The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,
If X and Y are the same type, then this is the type of the conditional Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression. Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression. Otherwise, no expression type can be determined, and a compile-time error occurs.
在我看来,在我的示例代码中,X 和 Y 必须属于同一类型,因为它们是同一实体 Func。那么为什么它不能编译呢?
最佳答案
问题发生了很大的变化,所以我原来的答案现在有点偏离了。
但是,问题本质上是一样的。 IE。 F
可能有任意数量的匹配委托(delegate)声明并且由于两个相同的委托(delegate)声明之间没有隐式转换 F
的类型无法转换为 Func<bool>
.
同样,如果你声明
private delegate void X();
private delegate void Y();
private static void Foo() {}
你做不到
X x = Foo;
Y y = x;
原答案:
它不起作用,因为不能将方法组分配给隐式类型变量。
var test = Func;
也不起作用。
原因是 Func
可以有任意数量的委托(delegate)类型.例如。 Func
匹配这两个声明(除了 Action
)
private delegate void X();
private delegate void Y();
要将隐式类型变量与方法组一起使用,您需要通过强制转换来消除歧义。
参见 archil's answer一个解决此问题的具体示例。也就是说,他展示了更正后的代码可能是什么样子 [假设您希望匹配的代表是 Action
].
关于c# - 为什么 "Func<bool> test = value ? F: F"不编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6015747/