抽象类中的公共事件 [英] public Event in abstract class

查看:80
本文介绍了抽象类中的公共事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在抽象类中声明了事件:

I have event declared in abstract class:

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的其他派生类中访问此事件:

I wanted to access this base class event in derived. Further I wanted to access this event in some other derived class of MyClass:

MyClass.ActionEvent += DerivedMethod()

请帮助我了解如何处理抽象类中定义的事件.

Please help me understand how to work with event defined in abstract classes.

推荐答案

这种方法可能很危险,请参见下文以获得更好的方法

只能从声明类中的引发(或显然检查是否为null)事件.这种保护扩展到派生类.

This approach could be dangerous, see below for a better one

Events can only be raised (or checked for null apparently) from within the declaring class. This protection extends to derived classes.

因此,解决方案是重新声明事件作为基类中抽象事件的实现.然后,您仍然可以根据需要通过基类引用使用它,并在派生类中引发/使用它:

Thus, the solution is to re-declare the event as an implementation of an abstract event in the base class. Then you can still use it via a base class reference as you want, and raise/use it in the derived class:

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)
        {
        }

    }
}

正确的方法

MSDN 建议编译器可能无法正确处理此方法.相反,您应该提供受 protected 保护的方法,以便派生类可以检查null,调用事件等:

Correct approach

MSDN Suggests that this approach may not be handled by the compiler correctly. Instead you should provide protected methods so derived classes can check for null, invoke the event, etc:

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())
        {}
    }
}

这篇关于抽象类中的公共事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆