Is it possible to 'overeride' (?) the way my delegate wrapper gets invoked? so instead of meAction.Invoke() I could just do meAction()?

StackOverflow https://stackoverflow.com/questions/22427162

Question

I have a delegate wrapper called SerializedAction

[Serializable]
public class SerializedAction
{
   private Action action;
   public void Add (Action handler) {...}
   public void Remove (Action handler) {...}
   public void Invoke () { Get().Invoke(); }
   public static SerializedAction operator +(SerializedAction action, Action handler) {...}
   public static SerializedAction operator -(SerializedAction action, Action handler) {...}
   private RebuildInvocationList() {...}
   private Action Get() {...}
   ...
}

I have managed to overload the +/- operators so I don't have to explicitly call Add and Remove - But whenever I want to invoke, I have to call Invoke - I was wondering if there was a way to invoke it like a normal delegate, i.e.

var meAction = new SerializedAction();
meAction += handler;
meAction(); // instead of meAction.Invoke()?

Is this possible somehow?

Thanks.

Was it helpful?

Solution

Unfortunately, this isn't possible in C#. The "()" syntax simply compiles to a call to Delagate.Invoke(); it isn't an overridable operator. Since normal C# classes can't extend either Delegate or MulticastDelegate, you can't therefore get the compiler to allow you to use the () syntax with your class. That said, it might be possible to do something like this with raw IL, by creating a type that extends MulticastDelegate and compiling it to a separate assembly that you then reference from your C# code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top