首页 文章

为什么不能推断出这些类型的论点? [重复]

提问于
浏览
6

可能重复:C#3.0泛型类型推断 - 将委托作为函数参数传递

为什么不能推断 Main 中调用中以下代码示例的类型参数?

using System;

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

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

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

这给出以下错误消息:

错误CS0411:无法从用法推断出方法Program.Method <T>(System.Action <T>)的类型参数 . 尝试显式指定类型参数 .

3 回答

  • 0

    问题是 Action (除了已经是类型;请重命名)实际上是一个可转换为委托类型 Action<int> 的方法组 . 类型推理引擎无法推断类型,因为方法组表达式是无类型的 . 如果您实际将方法组强制转换为 Action<int> ,则类型推断成功:

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

    这有效:

    static void Main(string[] args)
        {
            Method<int>(Action);
        }
    
        static void Action(int arg)
        {
            // ...
        }
    
        static void Method<T>(Action<T> action)
        {
            // ...
        }
    
  • 0

    只是把这是一个编译器我明白你的意思 .

    我认为这是因为 Action 用作方法组,但它不是 Action<int> 类型 .

    如果你把它投射到这种类型它工作:

    Method((Action<int>)Action);
    

相关问题