鉴于此代码:
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)无法弄清楚T是string.
这对我来说似乎是一个非常简单的案例,我发誓我在其他通用实用程序和扩展函数中依赖于更复杂的推理.我在这里错过了什么?
更新1:这是在C#4.0编译器中.我在VS2010中发现了这个问题,上面的示例来自我在LINQPad 4中制作的最简单的repro.
更新2:在可用的列表中添加了更多示例.
我想知道为什么当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)
我本以为我能够传递foo给bar编译器推断出Action<T>正在传递的函数的签名的类型,但这不起作用.但是我可以Action<int>在foo没有强制转换的情况下创建一个from ,所以有一个合理的原因,编译器也不能通过类型推断做同样的事情吗?