开发者

C# Infer generic type based on passing a delegate

开发者 https://www.devze.com 2023-04-04 07:06 出处:网络
I have the following code: public static class X { public static C Test<A,B,C>(this A a, Func<B,C> f)

I have the following code:

public static class X
{
    public static C Test<A,B,C>(this A a, Func<B,C> f)
        where C:class
    {
        return null;
    }

}

public class Bar
{
    public Bar()
    {
        this.Test(foo开发者_JAVA技巧); //this doesn't compile
        this.Test((Func<int, string>)foo);
        this.Test((int q) => "xxx");
    }

    string foo(int a) { return ""; }
}

Why doesn't the marked line compile? Does it have something to do with return type not being part of the signature?

But the third line does compile, which makes me guess the compiler turns it into something similiar to the second line...


Basically, the type inference process described in section 7.5.2 of the spec is relatively weak when it comes to method group conversions. In the annotated standard, in section 7.5.2.6 which talks about Output Type Inferences - including method groups - there's an annotation from Vladimir Reshetnikov stating:

This step [method group output type inference] applies only if all method type parameters occurring in the delegate parameter types are already fixed. Overload resolution does not try to select the best method based on incomplete type information.

I believe that's exactly the problem here - sure, you've only actually got one method you can call and the method group only contains a single method, but the type inference process isn't quite powerful enough to tie the two together.

0

精彩评论

暂无评论...
验证码 换一张
取 消