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
366 views
in Technique[技术] by (71.8m points)

c# - Why does "Func<bool> test = value ? F: F" not compile?

I have seen similar questions to this, but they involve different types so I think this is a new question.

Consider the following code:

public void Test(bool value)
{
    // The following line provokes a compiler error:
    // "Type of conditional expression cannot be determined because there is 
    // no implicit conversion between 'method group' and 'method group".

    Func<bool> test = value ? F : F;
}

public bool F()
{
    return false;
}

Now, according to the C# 3.0 Standard,

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

If X and Y are the same type, then this is the type of the conditional Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression. Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression. Otherwise, no expression type can be determined, and a compile-time error occurs.

It seems to me that in my sample code, X and Y must be of the same type, since they are the selfsame entity, Func. So why does it not compile?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The question was changed significantly, so my original answer is a bit off by now.

However, the problem is essentially the same. I.e. there could be any number of matching delegate declarations for F and since there is no implicit conversion between two identical delegate declarations the type of F cannot be converted to Func<bool>.

Likewise, if you declare

private delegate void X();
private delegate void Y();
private static void Foo() {}

You cannot do

X x = Foo;
Y y = x;

Original answer:

It doesn't work because method groups cannot be assigned to an implicitly typed variable.

var test = Func; doesn't work either.

The reason being that there could be any number of delegate types for Func. E.g. Func matches both of these declarations (in addition to Action)

private delegate void X();
private delegate void Y();

To use implicitly typed variables with method groups, you need to remove the ambiguity by casting.


See archil's answer for a concrete example of one way to fix this. That is, he shows what the corrected code might look like [assuming the delegate you desire to match is Action].


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

...