How to implement events through interface in C#?

前端 未结 1 1293
北恋
北恋 2021-02-07 15:47

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

1条回答
  •  孤独总比滥情好
    2021-02-07 16:02

    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

    0 讨论(0)
提交回复
热议问题