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

标签 c# .net generics c#-3.0 type-inference

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

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

The type arguments for method FirstClassFunctions.Functions.Apply<T1,T2,TR>(T1, System.Func<T1,T2,TR>, T2)' cannot be inferred from the usage. Try specifying the type arguments explicitly

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);
        }
    }

最佳答案

我认为这是 VS2008 C# 编译器在将方法组转换为委托(delegate)时无法正确推断所涉及类型的结果。@Eric Lippert 在他的帖子 C# 3.0 Return Type Inference Does Not Work On Method Groups 中讨论了此行为。 .

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

现在,类型推断的规则相当复杂,我远不是这方面的专家。如果我弄错了,希望有一些真正知识的人可以解决这个问题。

关于c# - 为什么 C# 编译器不自动推断此代码中的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4188875/

相关文章:

c# - 执行未转换对象的函数

c# - 对象当前正在别处使用 - 当 image.save

.net - 是否有用于读取 RAW 文件的良好 .NET 库?

c# - 跨域 iframe 中的安全错误

java - 如何将泛型类型指定为参数,例如 List/Map<T>?

c# - 将2个数字插入一个字节

c# - 仅当设置了属性时才应用样式

c# - 系统格式异常 : String was not recognized as a valid DateTime - when trying to convert MM/DD/YYYY

scala - 从必须实现类型类的方法返回值

c# - 为什么我不能在 C# 中使用隐式类型执行此操作?