0

I've written some calculate delegates which are passed as parameters.

private delegate int CalculateDelegator(int value1, int value2);
CalculateDelegator addWith = add;
CalculateDelegator divWith = div;

private static int add(int value1, int value2) {
    return value1 + value2;
}

private static int div(int value1, int value2) {
    return value1 / value2;
}

The method link(CalculateDelegator method, int value2) which receives addWith as parameter holds value1 and the method which calls link holds value2. So I call link() always with passing value2 as seperate paremeter.

Is there a way of passing the calculating method including the first parameter: link(addWith(value2))? (e.g. as a partial function like in Scala)

4

3 回答 3

1

您可以执行以下操作:

Func<int, int> partialMethod =
    value1 => addWith(value1, 5);

这样,partialMethod将接受一个参数并将其与内部“持有”值一起传递。

于 2013-07-24T11:19:23.303 回答
1

不,这样的事情在 C# 中是不可能直接实现的。

您可以执行以下操作:

int link(Func<int, int> addWithValue2)
{
    return addWithValue2(value1);
}

你可以这样称呼它:

link(v1 => addWith(v1, value2));

顺便说一句:我认为您所描述的概念称为柯里化,并且有一个项目试图将其引入 C#:https ://github.com/ekonbenefits/impromptu-interface/wiki/UsageCurry 。它基本上使用此答案中显示的方法。

于 2013-07-24T11:20:02.893 回答
0

As far as I understand your question, you would need to create an extension method for int:

public static LinkExtension
{
    public static void Link(this int value, CalculateDelegator method)
    {
        // Link action here
    }
}

So you just call value2.Link(addWith).

于 2013-07-24T11:25:27.990 回答