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

本文关键字:类似于 添加 对象 | 更新日期: 2023-09-27 18:19:14

我想问,你能做类似的事情吗?

Event += eventInstance;

Event是一个类

我想做一些类似委托的事情:

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

谢谢。

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

重载+操作符并组合委托。像这样:

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

你需要为你的类实现操作符重载。

class Write
{
    public static Write operator +(Write w1, Write w2)
    {
        // implementation, must return Write object
    }
}

可以。
创建一个operator +

你的类应该是不可变的,你可能想使用一个扁平的成员列表。