【发布时间】:2016-09-25 11:29:43
【问题描述】:
请不要与代码混淆,代码是错误的。专注于下面的粗体问题。
我一直在准备学习函数式编程,至少要为它的先决条件做好准备,我一直在研究扩展、函数和 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 扩展了我的整数“s”。我的计划是在上面的 CreateMethod() 中传递两个参数并将这两个参数乘以 's'
在上面的例子中,答案应该是 60。
你能帮我使用扩展程序吗?
【问题讨论】:
-
Func<int, int, int>接受 2 个输入参数并返回int。所以要调用它,你应该是fun(param1, param2)。您的扩展只需要一个参数(fn除外)。因此,您需要在CreatedMethod中添加其他参数。 -
@DovydasSopa 是的,你说得对,我忘了包括它。但即使我这样做。我将在哪里获得 param1 和 param2?查看代码。
-
首先不清楚你是否想要
Func<int, int, int>。如果您打算传递数字,为什么要这样声明? -
是的,我也想知道 - 你为什么要传递一个函数?你想做什么?
-
你要不要
s.CreatedMethod(2, 3, RegularMethod)?目前尚不清楚您为什么要这样做,除非CreatedMethod也在做其他事情......
标签: c# functional-programming extension-methods func chaining