Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

c# - Type of conditional expression cannot be determined (Func)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...