C#扩展方法作为接口实现

PJK*_*PJK 44 c# extension-methods interface multiple-inheritance

我想知道某个类的C#扩展方法是否可以作为接口的实现?我有什么:

一个表面:

public interface IEventHandler
{
    void Notify(SEvent ev, IEventEmmiter source);
}
Run Code Online (Sandbox Code Playgroud)

实现它的类:

class Sim : IEventHandler
{

    /*public void Notify(SEvent ev, IEventEmmiter source)
    {
        Console.WriteLine("Got notified: " + ev.Name);
    }*/

}
Run Code Online (Sandbox Code Playgroud)

还有一个包含扩展方法的类:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我希望有各种类与IEventHandler接口,接口的实现应该通过扩展方法来实现.

如果那是不可能的,是否可以明确定义Notify,然后将调用转发给扩展方法?

上面的代码基本上是一个多继承黑客.是否可以通过任何(其他)方式模拟此行为?

(我希望这是有道理的,我已经习惯了Ruby,这给了我很多时间.哦,我怎么能想念你,亲爱的混音......)

更新

呼叫转发很好地解决了它:

public void Notify(SEvent ev)
{
    ReflectiveEventDispatcher.Notify(this, ev,);
}
Run Code Online (Sandbox Code Playgroud)

Fem*_*ref 26

不,扩展方法不能作为接口的实现.扩展方法只是静态方法的语法糖,它将该类的实例作为第一个参数,因此不是特定类的成员,这是实现接口的要求.


jer*_*enh 12

这不可能按照你描述的方式来完成:C#方法调用解析将始终选择你的方法的具体实现,而不是扩展方法.

但是,我相信如果你不在界面中定义方法,你可以 - 某些 - 得到你想要的东西,但只是作为不同命名空间中的扩展方法.当然,这是"静态的",因为仍然会在编译时选择被调用的方法.

实际上,您可以选择通过右侧"using"指令调用的方法(类似于LINQ的工作原理)


SLa*_*aks 8

这是不可能的.

接口方法必须由实现类型本身实现.

扩展方法是纯粹的语言级概念(语法糖),并没有帮助.CLR本身完全不知道扩展方法,