“lambda 表达式”与“lambda 表达式”之间没有隐式转换 和“lambda 表达式”?
无法确定条件表达式的类型,因为“lambda 表达式”和“lambda 表达式”之间没有隐式转换
说什么? 有人可以向我解释一下这个编译错误吗? 这是生成它的代码:
protected override Func<System.IO.Stream> GetStream()
{
return someBool
? () => EmbeddedResourceExtractor.GetFile("SomeFile1.ext")
: () => EmbeddedResourceExtractor.GetFile("SomeFile2.ext");
}
这不是:
protected override Func<System.IO.Stream> GetStream()
{
return () => EmbeddedResourceExtractor.GetFile("SomeFile1.ext");
}
这也不是:
protected override Func<System.IO.Stream> GetStream()
{
if(someBool)
return () => EmbeddedResourceExtractor.GetFile("SomeFile1.ext");
return () => EmbeddedResourceExtractor.GetFile("SomeFile2.ext");
}
Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'
Say whaat? Could someone please explain this compile error to me? This is the code that produces it:
protected override Func<System.IO.Stream> GetStream()
{
return someBool
? () => EmbeddedResourceExtractor.GetFile("SomeFile1.ext")
: () => EmbeddedResourceExtractor.GetFile("SomeFile2.ext");
}
This does not:
protected override Func<System.IO.Stream> GetStream()
{
return () => EmbeddedResourceExtractor.GetFile("SomeFile1.ext");
}
And neither do this:
protected override Func<System.IO.Stream> GetStream()
{
if(someBool)
return () => EmbeddedResourceExtractor.GetFile("SomeFile1.ext");
return () => EmbeddedResourceExtractor.GetFile("SomeFile2.ext");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
条件表达式的类型必须作为一个整体来推断 - 并且 lambda 表达式始终必须转换为特定的委托或表达式树类型。
在后两个示例中,编译器知道它试图将 lambda 表达式转换为什么。 在第一个示例中,它首先尝试计算出整个条件表达式的类型。
不过,在其中一个分支中进行强制转换就足够了:
Sergio 的修复(现已删除,但包含在下面)将起作用如果您很乐意在函数执行时评估
someBool
被称为:根据时间的不同,有各种不同的方法来修复您实际给出的示例,例如,
我猜您的真实代码更复杂。
从某些方面来说,遗憾的是 C# 的类型推断不能更强大 - 但它已经相当复杂了。
The type of the conditional expression has to be inferred as a whole - and lambda expressions always have to be converted to a specific delegate or expression tree type.
In your latter two examples, the compiler knows what it's trying to convert the lambda expression to. In the first example, it tries to work out the type of the whole conditional expression first.
A cast in one of the branches would be enough though:
Sergio's fix (now deleted, but included below) will work if you were happy to evaluate
someBool
at the time the function is called:Depending on timing, there are all kinds of different ways of fixing the example you've actually given, e.g.
I'm guessing your real code is more complicated though.
It's a shame in some ways that C#'s type inference can't be more powerful - but it's already pretty complicated.