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

问题描述

无法确定的条件前pression类型,因为没有之间的lambda前pression'和'拉姆达前pression

说whaat?可能有人请解释这个编译错误给我?这是code产生的:

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


推荐答案

的类型的条件前pression的必须被推断为一个整体 - 和lambda前pressions总是要被转换为一个特定委托或前pression树类型。

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前pression转换。在第一个例子,它会尝试先制定出整个有条件恩pression的类型。

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

我猜你真正的code是更加复杂,但。

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

这是在某些方面是C#的类型推理不可能是更强大的一个耻辱 - 但它已经pretty复杂

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

这篇关于C#的lambda前pression'和'拉姆达前pression'之间的隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 22:13