如何通过C#中的接口实现事件? [英] How to implement events through interface in C#?
本文介绍了如何通过C#中的接口实现事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了一个问题:想象一下我有一个基于插件的系统。
I have a problem: imagine I have a plugin-based system.
我需要某种接口,我可以从每个插件中捕获事件,例如 IReporting
interface。
I need some kind of interface with which I could catch events from every plugin, which implements for example IReporting
interface.
(IReporting) object.OnSomeEvent += <.....>
但我找不到办法做到这一点。
But I can't find a way to do that.
推荐答案
而不是(IReporting)obj.XXX你应该写((IReporting)obj).XXX
Instead of (IReporting)obj.XXX you should write ((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();
关于插件框架,请查看具有良好架构的现有解决方案,例如 MEF
Regarding plugin framework take a look at existing solutions with good architecture, for example MEF
这篇关于如何通过C#中的接口实现事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文