【问题标题】:Why can't I pass just the name of a method where a similarly typed Func is expected?为什么我不能只传递需要类似类型 Func 的方法的名称?
【发布时间】:2010-07-08 09:16:06
【问题描述】:

为什么这个 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";
  }
}

【问题讨论】:

    标签: c# mono gmcs


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      相关资源
      最近更新 更多