我在抽象类中声明了事件:
public abstract class AbstractClass
{
public event Action ActionEvent;
}
public class MyClass : AbstractClass
{
private void SomeMethod()
{
//Want to access ActionEvent-- Not able to do so
if (ActionEvent != null)
{
}
}
}
我想在派生中访问这个基类事件。此外,我想在 MyClass 的其他派生类中访问此事件:
MyClass.ActionEvent += DerivedMethod()
请帮助我了解如何使用抽象类中定义的事件。
最佳答案
一个经常使用的模式如下所示(您会在 System.Windows.Forms
命名空间的类中看到很多)。
public abstract class MyClass
{
public event EventHandler MyEvent;
protected virtual void OnMyEvent(EventArgs e)
{
if (this.MyEvent != null)
{
this.MyEvent(this, e);
}
}
}
然后您可以像这样在派生类中使用它,可选择地扩展行为:
public sealed class MyOtherClass : MyClass
{
public int MyState { get; private set; }
public void DoMyEvent(bool doSomething)
{
// Custom logic that does whatever you need to do
if (doSomething)
{
OnMyEvent(EventArgs.Empty);
}
}
protected override void OnMyEvent(EventArgs e)
{
// Do some custom logic, then call the base method
this.MyState++;
base.OnMyEvent(e);
}
}
关于c# - 抽象类中的公共(public)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29831066/