C#-事件和接口 [英] C# - Events and Interfaces
问题描述
我有一个界面,其中包含多个事件
我有实现该接口的 base 类
我有第三类扩展了基类(我们称其为TheConcreteClass)
I have an interface with several events
I have base class implementing the interface
I have third class extending the base class (let's call it theConcreteClass)
问题:当我执行以下操作时: IMyInterface我= new theConcreteClass(),然后我订阅了任何事件( i.someEvent + = some_handler ;)事件处理程序从未调用,因为(可能)事件订阅已分配给基类而不是具体类,即使new()运算符创建了具体类.
problem: when i do something like: IMyInterface i = new theConcreteClass() and then i subscribe to any of the events (i.someEvent+=some_handler;) the event handlers never invoked because (probably) the event subscription was assigned to the base class and not to the concrete class even though the new() operator created the concrete class.
希望很清楚:)
有什么建议?
hope it was clear :)
any suggestions?
谢谢,
阿迪·巴尔达(Adi Barda)
thanks,
Adi Barda
推荐答案
您所描述的应该可以按预期工作.
What you are describing should work as expected.
您是否在隐藏基本实现的具体类中再次声明了事件?
Have you declared the events again in the concrete class hiding the base implementations?
您的代码应为:
public interface IInterface
{
event EventHandler TestEvent;
}
public class Base : IInterface
{
public event EventHandler TestEvent;
}
public class Concrete : Base
{
//Nothing needed here
}
回答您的评论:
To answer your comment:
标准做法是在基类上放置一个方法:
Standard practice is to place a method on the base class:
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();
}
}
此模式有助于集中用于触发事件,测试null等的任何逻辑,并通过覆盖方法使在子类中触发事件的时间变得容易.
This pattern helps centralise any logic for firing the event, testing for null etc, and makes it easy to hook into the time that the event fires in child classes by overriding the method.
这篇关于C#-事件和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!