I have implemented my own event registration for a client-server UI framework, much like in ASP.NET. I store an event’s name (e.g. “Click“) in a dictionary and as the value I remember
oEventHandler.Method.DeclaringType.AssemblyQualifiedName.ToString() + "." + oEventHandler.Method.Name.
Then to reinvoke the event handlers later on, I recreate the delegate:
var oEventHandler = Delegate.CreateDelegate( typeof( BLUIEventHandler ), oPage, sEventMethod, false )
and invoke it on the page:
oEventHandler.Invoke( oPage, this, oEventArgs );
This works fine for event handlers that are part of the ASPX page, like
var oTheButton = new UIButton();
oTheButton.Click += this.HandleClick;
private void HandleClick() {}
but fails for anonymous delegates:
var oTheButton = new UIButton();
oTheButton.Click += delegate {/* Will never be called. */};
The resulting string for a non-anonymous delegate is:
"MyTest.Rene.UI.Foo, BDRS, Version=8.10.1.19703, Culture=neutral, PublicKeyToken=null.HandleClick"
For an anonymous delegate it is:
"MyTest.Rene.UI.Foo+<>c__DisplayClass1, MyTest, Version=8.10.1.17866, Culture=neutral, PublicKeyToken=null.<OnInitializeLayout>oTheButton__0"
However when I try to recreate the anonymous delegate, I get a binding error.
Is there a way to get back to the anonymous delegate and invoke it?
That is never going to work for the general case of anonymous methods, since there is a very good chance that there are captured variables involved, and you will not know the values to capture (plus you have changed the nature: the original closure could update the captured variables – they aren’t isolated copies).
Personally, I think you should store the
Delegateinstance – not the name.EventHandlerListis a typical way of implementing this (along with uniqueobjectkeys per event).