开发者

Why can't these type arguments be inferred? [duplicate]

This question already has answers here: 开发者_如何学JAVA Closed 11 years ago.

Possible Duplicate:

C# 3.0 generic type inference - passing a delegate as a function parameter

Why can't the type arguments of the following code sample in the call in Main be inferred?

using System;

class Program
{
    static void Main(string[] args)
    {
        Method(Action);
    }

    static void Action(int arg)
    {
        // ...
    }

    static void Method<T>(Action<T> action)
    {
        // ...
    }
}

This gives the following error message:

error CS0411: The type arguments for method Program.Method<T>(System.Action<T>) cannot be inferred from the usage. Try specifying the type arguments explicitly.


The problem is that Action (aside from already being a type; please rename it) is actually a method group that is convertible to the delegate type Action<int>. The type-inference engine can't infer the type because method group expressions are typeless. If you actually cast the method group to Action<int>, then type-inference succeeds:

Method((Action<int>)Action); // Legal


This works:

    static void Main(string[] args)
    {
        Method<int>(Action);
    }

    static void Action(int arg)
    {
        // ...
    }

    static void Method<T>(Action<T> action)
    {
        // ...
    }


Just put this is a compiler I see what you mean.

I think it's because Action is used as a method group, but it's not of type Action<int>.

If you cast it to this type it works:

Method((Action<int>)Action);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜