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

时间:2011-12-30 02:22:54

标签: c# object delegates

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

Event += eventInstance;

活动是一个班级

我想做一些与代表类似的事情:

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

感谢。

3 个答案:

答案 0 :(得分:6)

重载+ operator并合并代表。像这样:

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

将打印

Write1
Write2
Write3

答案 1 :(得分:4)

您需要为您的班级实施operator overloading

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

答案 2 :(得分:3)

是。
只需创建一个operator +

您的课程应该是不可变的,您可能希望使用扁平的成员列表。