4

为什么这个 C# 不进行类型检查?在此示例中,我尝试将类型的方法string -> string作为Func<string, string>. 在仅传递适当类型函数的名称时能够省略 lambda 语法似乎是完全合理的。

using System;
using System.Linq;

class WeakInference
{
  public static void Main (string [] args)
  {
    // doesn't typecheck
    var hellos = args.Select (AppendHello); 

    // have to do this:
    // var hellos = args.Select (s => AppendHello (s));
  }

  static string AppendHello (string s)
  {
    return s + "hello";
  }
}
4

1 回答 1

6

您可以使用 C# 4 编译器。C# 3 编译器对方法组转换的类型推断较弱。您可以在此处阅读 Eric Lippert 的回答中的详细信息。我不完全清楚这是否意味着 C# 3 编译器实际上并未实现 C# 3 规范,或者规范本身是否在该区域的 3 和 4 之间发生了变化。与编译器是否按照您的意愿行事相比,这是一个相当学术的问题;)

(我刚刚测试过,你的程序不能用 VS 2008 编译,但可以用 VS 2010 编译。)

于 2010-07-08T09:24:31.603 回答