之间没有隐式转换吗

之间没有隐式转换吗

本文介绍了在“ lambda表达式”和“ lambda表达式”之间没有隐式转换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说白话吗?有人可以向我解释这个编译错误吗?这是产生它的代码:

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表达式”之间没有隐式转换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:50