gpt4 book ai didi

c# - 如何在 C# 中组合委托(delegate)

转载 作者:太空狗 更新时间:2023-10-29 20:00:32 25 4
gpt4 key购买 nike

我想实现一个方法,该方法采用两个 Action A1 和 Action A2 委托(delegate)并返回新的委托(delegate),将它们组合在一起。该方法的签名如下:

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));
}

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

最佳答案

我想你想要:

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); };
}

关于c# - 如何在 C# 中组合委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5088640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com