不起作用:
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中只有一个有类型[...]
- 否则,无法确定表达式类型,并发生编译时错误.