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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/465318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:29:18  来源:igfitidea点击:

How to implement events through interface in C#?

c#interface

提问by Lukas ?alkauskas

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 IReportinginterface.

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

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

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

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

采纳答案by aku

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