I was wondering if a C# extension method of some class could act as an implementation of interface? What do I have:
An iterface:
public interface IEventHandler
{
void Notify(SEvent ev, IEventEmmiter source);
}
A class that implements it:
class Sim : IEventHandler
{
/*public void Notify(SEvent ev, IEventEmmiter source)
{
Console.WriteLine("Got notified: " + ev.Name);
}*/
}
And a class that contains the extension method:
public static class ReflectiveEventDispatcher
{
public static void Notify(this IEventHandler handler, SEvent ev)
{
if (handler.GetType().GetMethod("Handle" + ev.Name) != null)
{
// C# WTF?
object[] prms = new object[0];
prms[0] = ev;
handler.GetType().GetMethod("Handle" + ev.Name).Invoke(handler, prms);
}
else
{
throw new System.NotImplementedException("This object doesn't have appropriate handler methods for event " + ev.Name);
}
}
}
Now, I want to have various classes with IEventHandler interface and the interfaces' implementation should be fulfilled by the extension method.
If that's not possible, is it possible to define the Notify explicitly and then just forward the call to the extension method?
The code above is basically a multiple inheritance hack. Is it possible to emulate this behaviour by any (other) means?
(I hope this makes sense, I'm used to Ruby and this is giving me really hard time. Oh, how do I miss you, my dear mixins...)
Call forwarding solved it pretty well:
public void Notify(SEvent ev)
{
ReflectiveEventDispatcher.Notify(this, ev,);
}
No, Extension methods can not act as implementation for an interface. Extensions methods are just syntactic sugar for a static method taking an instance of that class as the first parameter, thus not being a member of the specific class, which is a requirement for implementing an interface.
this can not be done the way you describe it: C# method call resolution will always choose the concrete implementation of your method, never the extension method.
However, I believe you can -somewhat- get what you want if you DON'T define the method in the interface, but simply as extension methods in different namespaces. Of course, this is "static", in that the method called will still be selected at compile time.
Practically speaking, you then select the method called through the right "using" directive (similar to how LINQ works)
This is not possible.
Interface methods must be implemented by the implementing type itself.
Extension methods are a purely language-level concept (syntax sugar), and won't help. The CLR itself is completely unaware of extension methods,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With