作为接口(interface)实现的 C# 扩展方法

标签 c# interface extension-methods multiple-inheritance

我想知道某个类的 C# 扩展方法是否可以充当接口(interface)的实现? 我有什么:

一个接口(interface):

public interface IEventHandler
{
    void Notify(SEvent ev, IEventEmmiter source);
}

实现它的类:

class Sim : IEventHandler
{

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

}

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

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);
        }
    }
}

现在,我想要各种带有 IEventHandler 接口(interface)的类,接口(interface)的实现应该由扩展方法来实现。

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

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

(我希望这是有道理的,我已经习惯了 Ruby,这让我很难过。哦,我多么想念你,我亲爱的混入...)

更新

调用转移很好地解决了这个问题:

public void Notify(SEvent ev)
{
    ReflectiveEventDispatcher.Notify(this, ev,);
}

最佳答案

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

关于作为接口(interface)实现的 C# 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4832038/

相关文章:

mysql - MS SQL 数据库管理/IDE

c# - 在 C# 中合并多个列表

c# - 如何在扩展方法中获取 'this' 参数的泛型类型参数?

c# - 如何使用扩展方法Join()?

c# - 限制 Linq 列表中返回的结果数

c# - Silverlight:将服务调用和文件处理移至后台线程

interface - 如何在与主机相同的网络中创建macvlan网络接口(interface)?

C# 到 Excel - 自定义格式?

C# 方法错误 : Unreachable code detected and not all code paths return a value”

c++ - 在抽象层次结构的具体实例上执行契约