Emulate IDispatchEx in C #

C # 3.0. Extension methods add extensions to the base type that invokes this method on all instances of that Type legal.

Now the JavaScript I know implements IDispatchEx through which methods can be added to a specific instance.

So how do I add a set of methods to an "instance" of a C # class? I know this is a sacred military territory with dynamic and static languages. :) Let me make it clear that my intention is NOT.

I just want to add a set of events to an interface depending on the class that implements that interface.

I was able to do this with Generics

inteface ISample<T> { T SupportedEvents; }  

class Sample : ISample<UIWidgetEvent>   {   }  
class Sample2 : ISample<NonVisualUIWidget> { }

class UIWidgetEvent { public EventHandler Clicked; }  
class NonVisualUIWidget {public EventHandler Expired;}

class TestSample
{  
    public void Test()
    {  
        new Sample().SupportedEvents.Clicked += ...
        new Sample2().SupportedEvents.Expired += ...
    }  
}  

      

Then I didn't like it SupportedEvents

I want to say

new Sample().Clicked +=...

      

Then I thought that JavaScript (I know C#

not JS

:)) ... and IDispatchEx

, IL Weaving

, Reflection.Emit

and etc. etc and thoughts might be there a way to do it ... [Design-time support would be nice, but I can live without it

Yes, I could probably do this "instance increase" with the visitor template. [Not sure if I can get some syntactic sugar though]

Comments?

0


source to share


1 answer


Well, you can instantiate a DynamicMethod for your "new" methods, but statically bind them to an existing instance at runtime because it simply won't compile.

You might (I haven't tried this) be able to emit opcodes into an in-memory assembly, but that is as far from being "syntactically sweet" as you can get (would involve a lot of thinking and InvokeMember, I would think )

It might also be worth looking into extension methods - although I've never tried adding events or similar event methods using extension methods ... and they are only 3.5, so this might limit you.



The best "pure C #" implementation is probably very similar to what you already have with a generic / interface setup ...

Honestly, if you're looking for something with real "dynamic support" like this, I would do things like this in a DLR capable language (like IronPython) and call it from your C # stuff.

+2


source







All Articles