use*_*719 5 c# events delegates abstract-class action
我在抽象类中声明了事件:
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)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想在派生中访问此基类事件.此外,我想在MyClass的其他派生类中访问此事件:
MyClass.ActionEvent += DerivedMethod()
Run Code Online (Sandbox Code Playgroud)
请帮助我了解如何使用抽象类中定义的事件.
Mar*_*llo 10
一个常用的模式就像下面这样(你会在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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在这样的派生类中使用它,可选择扩展行为:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
仅可以从声明类中引发事件(或显然检查是否为null)。这种保护扩展到派生类。
因此,解决方案是将事件重新声明为基类中抽象事件的实现。然后,您仍然可以根据需要通过基类引用使用它,并在派生类中引发/使用它:
public abstract class AbstractClass
{
public abstract event Action ActionEvent;
}
public class MyClass : AbstractClass
{
public override event Action ActionEvent;
private void SomeMethod()
{
//Want to access ActionEvent-- Now you can!
if (ActionEvent != null)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
MSDN建议编译器可能无法正确处理此方法。相反,您应该提供protected方法,以便派生类可以检查null,调用事件等:
public abstract class AbstractClass
{
public event Action ActionEvent;
protected bool EventIsNull()
{
return ActionEvent == null;
}
}
public class MyClass : AbstractClass
{
private void SomeMethod()
{
//Want to access ActionEvent-- Now you can!
if (!EventIsNull())
{}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6180 次 |
| 最近记录: |