如何通过C#中的接口实现事件?

时间:2022-11-04 17:50:59

I have a problem: imagine I have a plugin-based system.

我有一个问题:想象一下我有一个基于插件的系统。

I need some kind of interface with which I could catch events from every plugin, which implements for example IReporting interface.

我需要某种接口,我可以从每个插件中捕获事件,例如实现IReporting接口。

(IReporting) object.OnSomeEvent += <.....>

But I can't find a way to do that.

但我找不到办法做到这一点。

1 个解决方案

#1


Instead of (IReporting)obj.XXX you should write ((IReporting)obj).XXX

而不是(IReporting)obj.XXX你应该写((IReporting)obj).XXX

public interface IFoo
{
    event EventHandler Boo;
}

class Foo : IFoo
{
    public event EventHandler Boo;
    public void RaiseBoo()
    {
        if (Boo != null)
            Boo(this, EventArgs.Empty);
    }
}

...

private void TestClass_Boo(object sender, EventArgs e)
{
    throw new NotImplementedException();
}

    ...

   object o = new Foo();
   ((IFoo)o).Boo += TestClass_Boo;
   ((Foo)o).RaiseBoo();

Regarding plugin framework take a look at existing solutions with good architecture, for example MEF

关于插件框架,请查看具有良好架构的现有解决方案,例如MEF

#1


Instead of (IReporting)obj.XXX you should write ((IReporting)obj).XXX

而不是(IReporting)obj.XXX你应该写((IReporting)obj).XXX

public interface IFoo
{
    event EventHandler Boo;
}

class Foo : IFoo
{
    public event EventHandler Boo;
    public void RaiseBoo()
    {
        if (Boo != null)
            Boo(this, EventArgs.Empty);
    }
}

...

private void TestClass_Boo(object sender, EventArgs e)
{
    throw new NotImplementedException();
}

    ...

   object o = new Foo();
   ((IFoo)o).Boo += TestClass_Boo;
   ((Foo)o).RaiseBoo();

Regarding plugin framework take a look at existing solutions with good architecture, for example MEF

关于插件框架,请查看具有良好架构的现有解决方案,例如MEF