I want to ask, can you do something similar to this?
Event += eventInstance;
Event is a class
I want to do something similar to delegates:
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();
Thanks.
Overload the + operator and combine the delegates. Something like this:
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);
}
}
And using it like so:
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();
Will print
Write1 Write2 Write3
You need to implement operator overloading for your class.
class Write
{
public static Write operator +(Write w1, Write w2)
{
// implementation, must return Write object
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With