相关疑难解决方法(0)

为什么C#不能从这个看似简单明显的案例中推断出类型

鉴于此代码:

class C
{
    C()
    {
        Test<string>(A); // fine
        Test((string a) => {}); // fine
        Test((Action<string>)A); // fine

        Test(A); // type arguments cannot be inferred from usage!
    }

    static void Test<T>(Action<T> a) { }

    void A(string _) { }
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨Test(A)无法弄清楚Tstring.

这对我来说似乎是一个非常简单的案例,我发誓我在其他通用实用程序和扩展函数中依赖于更复杂的推理.我在这里错过了什么?

更新1:这是在C#4.0编译器中.我在VS2010中发现了这个问题,上面的示例来自我在LINQPad 4中制作的最简单的repro.

更新2:在可用的列表中添加了更多示例.

c#

67
推荐指数
3
解决办法
3303
查看次数

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# ×2

c#-3.0 ×1

delegates ×1

generics ×1

type-inference ×1