如何在 C# 中组合委托

发布于 2024-10-18 22:44:23 字数 384 浏览 3 评论 0原文

我想实现一个方法,该方法接受两个 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));
}

该方法的可能实现是什么?

I want to implement a method which takes two Action A1 and Action A2 delegates and returns new delegate, which combines them. The signature of he method is the following:

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

So, instead of saying

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

I want to be able to write:

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

What is the possible implementation of this method can be?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三生一梦 2024-10-25 22:44:23

我想你想要:

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

I think you want:

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

Usage:

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

EDIT: By the way, I noticed you mentioned in a comment that "taking arguments individually would be even more preferable". In that case, you can do:

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); };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文