c# - 为什么 "Func<bool> test = value ? F: F"不编译?

标签 c#

我看到过类似的问题,但是它们涉及不同的类型,所以我认为这是一个新问题。

考虑以下代码:

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/

相关文章:

c# - Visual Studio 2010 C# "already defined a member with same parameter types error."

c# - 在此 Linq 查询中使用正则表达式?

c# - 我怎样才能实现我自己的外部类型?

c# - 将日期转换为字符串格式 yyyy-mm-dd HH :MM:SS - C#

c# - 是否可以在不注册自身的情况下引用 COM DLL?

c# - 带有 Func() 参数的 ASP.NET Core 日志记录

c# - 在发布版本 (C#) 中如何停止对调试函数调用中的参数求值

c# - 在 asp.net 后面的代码中访问类型文件的输入控件

c# - 使用 C# 在 Windows Phone 8.0 中的 TextBlock 中的超链接

c# - DateTime.ParseExact 具有可变的秒数