简体   繁体   中英

How to implement events through interface in C#?

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) object.OnSomeEvent += <.....>

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM