为什么C#编译器不会自动推断出此代码中的类型?

Clu*_*der 11 .net c# generics type-inference c#-3.0

为什么C#编译器不能推断FooExt.Multiply()满足签名的事实Functions.Apply()?我必须为代码指定一个单独的委托变量类型Func<Foo,int,int>才能工作......但似乎类型推断应该处理这个问题.我错了吗?如果是这样,为什么?

编辑:收到的编译错误是:

FirstClassFunctions.Functions.Apply<T1,T2,TR>(T1, System.Func<T1,T2,TR>, T2)'无法从用法中推断出方法的类型参数.尝试显式指定类型参数

namespace FirstClassFunctions  {
    public class Foo  {
        public int Value { get; set; }

        public int Multiply(int j) {
            return Value*j;
        }
    }

    public static class FooExt  {
        public static int Multiply(Foo foo, int j) {
            return foo.Multiply(j);
        }
    }

    public static class Functions  {
        public static Func<TR> Apply<T1,T2,TR>( this T1 obj, 
                                                Func<T1,T2,TR> f, T2 val ) {
            return () => f(obj, val);
        }
    }


    public class Main  {
        public static void Run()  {
            var x = new Foo {Value = 10};
            // the line below won't compile ...
            var result = x.Apply(FooExt.Multiply, 5);
            // but this will:
            Func<Foo, int, int> f = FooExt.Multiply;
            var result = x.Apply(f, 5);
        }
    }
Run Code Online (Sandbox Code Playgroud)

LBu*_*kin 5

我相信这是VS2008 C#编译器在将方法组转换为委托时无法正确推断所涉及的类型的结果.@Eric Lippert在他的帖子C#3.0中讨论了这种行为.返回类型推断在方法组上不起作用.

如果我没记错的话,在新的C#编译器中进行了一些改进,这是VS2010的一部分,它扩展了可以进行方法组推理的情况.

现在,类型推断的规则非常复杂,而且我远不是这个主题的专家.如果我弄错了,希望有真正知识的人可以解决这个问题.