在C#中,为什么不?:运算符使用lambda或方法组?

Aar*_*ide 20 c# lambda

不起作用:

Func<string, byte[]> getFileContents = (Mode != null && Mode.ToUpper() == "TEXT")
            ? TextFileContents
            : BinaryFileContents;

private static byte[] BinaryFileContents(string file)
{
    return System.IO.File.ReadAllBytes(file);
}

private static byte[] TextFileContents(string file)
{
    using (var sourceStream = new StreamReader(file))
    {
        return Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是

方法组和方法组之间没有隐式转换

作品:

Func<string, byte[]> getFileContents2;
if (Mode != null && Mode.ToUpper() == "TEXT")
{
   getFileContents2 = TextFileContents;
}
else
{
   getFileContents2 = BinaryFileContents;
}
Run Code Online (Sandbox Code Playgroud)

我只是好奇为什么?我错过了什么吗?

Jon*_*eet 29

匿名函数和方法组本身没有类型 - 它们只能转换委托类型(以及某些lambda表达式的表达式树类型).

对于条件运算符来确定表达式的整体类型,第二或第三个操作数中的至少一个必须具有类型.您可以将它们中Func<string, byte[]>的任何一个转换为,并且编译器会发现它可以将另一个转换为相同的类型,并且很高兴.

例如:

Func<string, byte[]> getFileContents = DateTime.Now.Hour > 10
    ? (Func<string, byte[]>) TextFileContents
    : BinaryFileContents;
Run Code Online (Sandbox Code Playgroud)

从C#5规范的第7.14节:

?:运算符的第二个和第三个操作数x和y控制条件表达式的类型.

  • 如果x有X型,y有Y型,那么[...]
  • 如果x和y中只有一个有类型[...]
  • 否则,无法确定表达式类型,并发生编译时错误.

  • @billisphere:很高兴它有所帮助:)我花了很长时间才得到它.(同样适用于`null`文字,顺便说一句.*大多数*表达式都有类型.) (2认同)
  • @MaximeTremblay-Savard Jon至少每月回答一次这个问题...你应该找到Jon或Eric Lippert相对简单的完全重复 - 比如http://stackoverflow.com/questions/263151/lambdas-and-the-conditional-operator -weird-问题 (2认同)