Why can't these type arguments be inferred?

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

这工作:

    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);
链接地址: http://www.djcxy.com/p/51780.html

上一篇: 为什么C#不推断我的泛型?

下一篇: 为什么不能推断这些类型的参数?