【问题标题】:Why doesn't the C# compiler automatically infer the types in this code?为什么 C# 编译器不自动推断此代码中的类型?
【发布时间】:2010-11-15 21:14:38
【问题描述】:

为什么 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);
        }
    }

【问题讨论】:

  • 以下应该也可以工作:x.Apply(new Func&lt;Foo, int, int&gt;(FooExt.Multiply), 5)。什么是编译错误?
  • 在 .NET 4.0 中对我来说似乎编译得很好。
  • 您确定这是您使用的确切代码吗?为了我们的利益,您还没有“简化”它?
  • 是的,C# 3.0 编译器不处理这个问题,4.0 编译器可以处理,即使目标是 .NET 3.5。

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


【解决方案1】:

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

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

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

【讨论】:

  • @Eric Lippert:感谢您的确认。顺便说一句,我想我记得你在博客上写过关于最新 C# 编译器中类型推断的改进,但我似乎在你的博客上找不到任何关于这种效果的文章……也许我是这么想的。
  • 我提到我们要修复它,这里:blogs.msdn.com/b/ericlippert/archive/2008/05/28/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 2021-03-11
  • 1970-01-01
相关资源
最近更新 更多