在“ lambda表达式”和“ lambda表达式”之间没有隐式转换吗?

编程入门 行业动态 更新时间:2024-10-20 16:38:56
本文介绍了在“ lambda表达式”和“ lambda表达式”之间没有隐式转换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

由于'lambda表达式'和'lambda表达式'之间没有隐式转换,因此无法确定条件表达式的类型

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"); }

这不是:

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"); }

推荐答案

条件表达式的类型必须从整体上进行推断-而且lambda表达式必须始终转换为特定的委托或表达式树类型。

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.

在后两个示例中,编译器知道什么它正在尝试将lambda表达式转换为。在第一个示例中,它首先尝试计算整个条件表达式的类型。

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:

protected override Func<Stream> GetStream() { return someBool ? (Func<Stream>) (() => EmbeddedResourceExtractor.GetFile("SomeFile1.ext")) : () => EmbeddedResourceExtractor.GetFile("SomeFile2.ext"); }

Sergio的修复程序(现已删除,但包含在下面)将在下运行您很高兴在调用函数时评估 someBool :

Sergio's fix (now deleted, but included below) will work if you were happy to evaluate someBool at the time the function is called:

protected override Func<Stream> GetStream() { return () => someBool ? EmbeddedResourceExtractor.GetFile("SomeFile1.ext") : EmbeddedResourceExtractor.GetFile("SomeFile2.ext"); }

根据时间的不同,可以使用各种不同的方式来修复示例实际上已经给出了例如

Depending on timing, there are all kinds of different ways of fixing the example you've actually given, e.g.

protected override Func<Stream> GetStream() { string name = someBool ? "SomeFile1.ext" : "SomeFile2.ext"; return () => EmbeddedResourceExtractor.GetFile(name); }

我想您的真实代码会更复杂。

I'm guessing your real code is more complicated though.

从某种程度上来说,C#的类型推断再强大不过了,但这已经很复杂了。

It's a shame in some ways that C#'s type inference can't be more powerful - but it's already pretty complicated.

更多推荐

在“ lambda表达式”和“ lambda表达式”之间没有隐式转换吗?

本文发布于:2023-11-08 07:38:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568753.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   隐式   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!