C# - 事件和接口

Adi*_*rda 0 c# events interface

我有一个接口有几个事件
我有类实现接口
我有第三类扩展基类(让我们称之为theConcreteClass)

问题:当我做类似的事情: IMyInterface i = new theConcreteClass() 然后我订阅任何事件(i.someEvent + = some_handler ;)事件处理程序从未调用,因为(可能)事件订阅被分配给基类而不是具体类,即使new()运算符创建了具体类.

希望很明显:)
任何建议?

谢谢,
阿迪巴尔达

Mar*_*ris 6

您所描述的内容应该按预期工作.

您是否在隐藏基本实现的具体类中再次声明了事件?

你的代码应该是:

public interface IInterface
{
    event EventHandler TestEvent;
}

public class Base : IInterface
{
    public event EventHandler TestEvent;
}

public class Concrete : Base
{
   //Nothing needed here
}
Run Code Online (Sandbox Code Playgroud)

回答你的评论:

标准做法是在基类上放置一个方法:

public class Base : IInterface
{
    public event EventHandler TestEvent;

    protected virtual void OnTestEvent()
    {
        if (TestEvent != null)
       {
           TextEvent(this, EventArgs.Empty);
       }
    }
}

public class Concrete : Base
{
   public void SomethingHappened()
   {
       OnTestEvent();
   }
}
Run Code Online (Sandbox Code Playgroud)

这种模式有助于集中任何触发事件的逻辑,测试null等,并通过覆盖方法,轻松挂钩事件在子类中触发的时间.