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

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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top