【问题标题】:How to combine delegates in C#如何在 C# 中组合委托
【发布时间】:2011-02-23 08:43:45
【问题描述】:

我想实现一个方法,它接受两个 Action A1 和 Action A2 委托并返回新委托,它将它们结合起来。他方法的签名如下:

public static Action<Tuple<T1,T2>> CombineWith<T1,T2>(this Action<T1> a1, Action<T2> a2)

所以,不要说

{
 A1(t1);
 A2(t2);
}

我希望能够写作:

{
A1.CombineWith(A2)(Tuple.Create(t1,t2));
}

这个方法的可能实现是什么?

【问题讨论】:

  • 返回一个以元组作为参数的动作是否至关重要?还是返回一个单独接受每个参数的操作也可以?
  • 实际上,单独接受参数会更可取。

标签: c# .net generics delegates functional-programming


【解决方案1】:

我想你想要:

public static Action<Tuple<T1,T2>> CombineWith<T1,T2>
            (this Action<T1> action1, Action<T2> action2)
{
    //null-checks here.

    return tuple => {
                       action1(tuple.Item1);
                       action2(tuple.Item2);
                    };
}

用法:

Action<int> a1 = x => Console.Write(x + 1);
Action<string> a2 = x => Console.Write(" " + x + " a week");

var combined = a1.CombineWith(a2);

// output: 8 days a week
combined(Tuple.Create(7, "days"));

编辑:顺便说一句,我注意到您在评论中提到“单独提出论点会更可取”。在这种情况下,您可以这样做:

public static Action<T1, T2> CombineWith<T1, T2>
            (this Action<T1> action1, Action<T2> action2)
{
    //null-checks here.

    return (x, y) => { action1(x); action2(y); };
}

【讨论】:

  • 谢谢。这正是我想要的!
猜你喜欢
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
  • 2019-10-07
  • 2010-09-20
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多