功能的功能是一个方向,而不是另一个方向

Joe*_*Joe 6 c# functional-programming

我正在尝试编写一个函数,它将函数作为其参数之一 - 我以前做过很多次的任务.这很好用:

int RunFunction(Func<int,int> f, int input) {
    return f(input);
}
int Double(int x) {
    return x*2;
}

// somewhere else in code
RunFunction(Double,5);
Run Code Online (Sandbox Code Playgroud)

然而,这不起作用:

public static class FunctionyStuff {
    public static int RunFunction(this Func<int,int> f, int input) {
        return f(input);
    }
}

// somewhere else in code
Double.RunFunction(5);
Run Code Online (Sandbox Code Playgroud)

知道为什么第一个有效,第二个没有?

Jon*_*eet 5

第一个版本是执行方法组转换,作为"参数参数"匹配的一部分.扩展方法不会发生此转换.lambda表达式也是如此 - 你无法写:

((int x) = > x * 2).RunFunction(10);
Run Code Online (Sandbox Code Playgroud)

无论是.

C#4规范的第7.6.5.2节给出了扩展方法调用的详细信息.它首先要求方法调用是以下形式之一:

expr.identifier ( )
expr.identifier ( args )
expr.identifier < typeargs > ( )
expr.identifier < typeargs > ( args )
Run Code Online (Sandbox Code Playgroud)

然后在此规则中使用表达式()的类型expr:

扩展方法C中 .M Ĵ合格如果

  • [...]
  • expr到M j的第一个参数的类型存在隐式标识,引用或装箱转换.

该规范的注释版本包括Eric Lippert的评论:

此规则确保使扩展方法double不会扩展int.它还确保在匿名函数或方法组上不定义任何扩展方法.