gpt4 book ai didi

C# 添加对象(类似于委托(delegate))

转载 作者:太空狗 更新时间:2023-10-29 22:16:54 25 4
gpt4 key购买 nike

我想问一下,你能做类似这样的事情吗?

Event += eventInstance;

事件是一个类

我想做一些类似于委托(delegate)的事情:

Write write1 = new Write(() => Console.WriteLine("Write1"));
Write write2 = new Write(() => Console.WriteLine("Write2"));
Write write3 = new Write(() => Console.WriteLine("Write3"));

Write write = write1 + write2 + write3;
write();

谢谢。

最佳答案

重载 + operator并合并委托(delegate)。像这样:

public class Write
{
private readonly Action _act;

public Write(Action act)
{
_act = act;
}

public void Invoke()
{
_act();
}

public static Write operator +(Write left, Write right)
{
//Do appropriate null-checking.
var del = (Action)Delegate.Combine(left._act, right._act);
return new Write(del);
}
}

像这样使用它:

Write write1 = new Write(() => Console.WriteLine("Write1"));
Write write2 = new Write(() => Console.WriteLine("Write2"));
Write write3 = new Write(() => Console.WriteLine("Write3"));

Write writeall = write1 + write2 + write3;
writeall.Invoke();

将打印

Write1Write2Write3

关于C# 添加对象(类似于委托(delegate)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8675554/

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