C#扩展使用函数Func作为参数

时间:2016-05-27 08:07:50

标签: c# functional-programming extension-methods func chaining

请不要与代码混淆,代码错误。专注于下面的大胆问题。

我一直在准备学习函数式编程,至少已经为它的先决条件做好了准备,我一直在研究扩展,函数和lambda表达式。

以下代码无法正常工作我只是认为应该如何编码:

程序:

class Program
{
    static void Main(string[] args)
    {
        int s = 10;
        int t = s.CreatedMethod(2, 3); // <-- the one that calls the extension
        Console.WriteLine(t.ToString());
        Console.ReadLine();
    }


    static int RegularMethod(int v1, int v2)
    {
        return v1 * v2; // <-- I also wanted to multiply int 's' like this s*v1*v2
    }
}

扩展:

public static class Extension
{
    public static int CreatedMethod(this int number, Func<int, int, int> fn) 
    { 
       // I'm expecting that the code here will read the 
       // RegularMethod() above
       // But I don't know how to pass the parameter of the function being passed
       return @fn(param1, param2)// <-- don't know how to code here ??
    } 
}

正如您所看到的,CreateMethod扩展了我的整数&#39; s。我的计划是在上面的CreateMethod()中传递这两个参数,并将这两个参数乘以&#39;

在上面的示例中,答案应为60。

你能帮助我使用扩展吗?

2 个答案:

答案 0 :(得分:3)

这可能是你正在寻找的东西,但将函数作为参数传递或者我只是遗漏了一些东西是没有意义的。无论如何,它有效:

class Program
{
    static void Main(string[] args)
    {
        int s = 10;
        // the function we're passing as a parameter will multiply them
        // then return the result
        int t = s.CreatedMethod((param1, param2) => param1 * param2);
        // or you can use this since the method signature matches:
        // int t = s.CreatedMethod(RegularMethod);
        Console.WriteLine(t.ToString()); // outputs "60"
        Console.ReadLine();
    }

    static int RegularMethod(int v1, int v2)
    {
        return v1 * v2; // <-- I also wanted to multiply int 's' like this s*v1*v2
    }
}

public static class Extension
{
    public static int CreatedMethod(this int number, Func<int, int, int> fn)
    {
        return number * fn.Invoke(2, 3);
    }
}

跟进OP的评论:如果您不想对值进行硬编码,那么您需要将CreateMethod的签名更改为:

public static int CreatedMethod(this int number, int val1, int val2, Func<int, int, int> fn) 

然后像这样调用Invoke

fn.invoke(val1, val2)

答案 1 :(得分:1)

扩展可能如下所示:

public static int CreatedMethod(this int number1, int number2, Func<int, int, int> fn) {
    fn(number1, number2);
}

然后打电话:

var s = 10;
var t = s.CreatedMethod(2, RegularMethod).
    CreatedMethod(3, RegularMethod);

首先使用RegularMethod10致电2,然后使用203进行第二次致电。

其他方式是使用

这样的扩展名
public static int CreatedMethod(this int number1, int number2, int number3, Func<int, int, int> fn) {
    fn(fn(number1, number2), number3);
}

并打电话给

var s = 10;
var t = s.CreatedMethod(2, 3, RegularMethod);