相关疑难解决方法(0)

C#3.0泛型类型推断 - 将委托作为函数参数传递

我想知道为什么当C#3.0编译器可以隐式地为同一方法创建委托时,它作为参数传递给泛型函数时无法推断方法的类型.

这是一个例子:

class Test
{
    static void foo(int x) { }
    static void bar<T>(Action<T> f) { }

    static void test()
    {
        Action<int> f = foo; // I can do this
        bar(f); // and then do this
        bar(foo); // but this does not work
    }   
}
Run Code Online (Sandbox Code Playgroud)

我本以为我能够传递foobar编译器推断出Action<T>正在传递的函数的签名的类型,但这不起作用.但是我可以Action<int>foo没有强制转换的情况下创建一个from ,所以有一个合理的原因,编译器也不能通过类型推断做同样的事情吗?

c# generics delegates type-inference c#-3.0

23
推荐指数
4
解决办法
9498
查看次数

标签 统计

c# ×1

c#-3.0 ×1

delegates ×1

generics ×1

type-inference ×1