I am trying to implement a generic Wrapper-Class for Qt’s class system using C#’s DynamicObject. However, I want to write the following code:
dynamic obj = new SomeWrapperClass(....); // This extends DynamicObject
obj.OnMyEvent += (Action)(() => Console.WriteLine("DO something!"));
The above is valid code according to VS2010 (the explicit cast to Action is required), but how exactly do i “catch” that statement using DynamicObject’s methods?
I tried implementing TryGetMember() and it gets called for the statement, but I have no idea what I have to return to make it work.
Any hints?
Reflector is your friend on this one. The code generated for your second line looks something like this (approximately):
If you can’t use a real event for
OnMyEvent(in which case you can lean on the defaultDynamicObjectimplementation), then you’ll need to return something that implementsAddAssignreturning something like a multicast delegate. I’d suggest the former, if possible…For fun, here’s a hackish example that dynamically binds OnMyEvent to OnMyOtherEvent: