条件表达式的类型无法确定(Func) [英] Type of conditional expression cannot be determined (Func)

查看:96
本文介绍了条件表达式的类型无法确定(Func)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当将方法分配给 Func -type时,我得到编译错误无法确定条件表达式的类型,因为没有隐式转换在'方法组'和'方法组'之间

When assigning a method to a Func-type, I get the compilation error Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'.

这只会发生在? :运算符。代码:

This only happens with the ? : operator. The code:

public class Test
{
    public static string One(int value)
    {
        value += 1;
        return value.ToString();
    }
    public static string Two(int value)
    {
        value += 2;
        return value.ToString();
    }
    public void Testing(bool which)
    {
        // This works
        Func<int, string> actionWorks;
        if (which) actionWorks = One; else actionWorks = Two;

        // Compilation error on the part "One : Two"
        Func<int, string> action = which ? One : Two;
    }
}

我发现有关信息共同和矛盾,但我看不出如何适用于上述情况。为什么这不工作?

I found some information about co- and contravariance, but I don't see how that applies to the situation above. Why doesn't this work?

推荐答案

您需要显式提供至少一个方法组的签名。但是,在这样做之后,编译器将允许您将 action 声明为隐式类型的本地:

You need to explicitly provide the signature of at least one method group. However, after doing it the compiler will allow you to declare action as an implicitly-typed local:

var action = which ? (Func<int, string>)One : Two;

发生这种情况的原因是返回类型 operator? code>不是根据您尝试分配给它而是基于两个表达式的类型推算的。如果类型相同或两者之间存在隐式转换,则编译器会成功推出返回类型;否则,它抱怨说没有转换。

The reason this happens is that the return type of operator ?: is not deduced based on what you are trying to assign it to, but based on the types of the two expressions. If the types are the same or there is an implicit conversion between them, the compiler deduces the return type successfully; otherwise, it complains that there is no conversion.

这篇关于条件表达式的类型无法确定(Func)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆