C#:引发继承的事件 [英] C#: Raising an inherited event

查看:34
本文介绍了C#:引发继承的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下事件的基类:

I have a base class that contains the following events:

public event EventHandler Loading;
public event EventHandler Finished;

在继承自该基类的类中,我尝试引发事件:

In a class that inherits from this base class I try to raise the event:

this.Loading(this, new EventHandler()); // All we care about is which object is loading.

我收到以下错误:

事件 'BaseClass.Loading' 只能出现在 += 或 -= (BaseClass') 的左侧

我假设我不能像其他继承成员一样访问这些事件?

I am assuming I cannot access these events the same as other inherited members?

推荐答案

你要做的,是:

在您的基类(您已在其中声明事件)中,创建可用于引发事件的受保护方法:

In your base class (where you have declared the events), create protected methods which can be used to raise the events:

public class MyClass
{
   public event EventHandler Loading;
   public event EventHandler Finished;

   protected virtual void OnLoading(EventArgs e)
   {
       EventHandler handler = Loading;
       if( handler != null )
       {
           handler(this, e);
       }
   }

   protected virtual void OnFinished(EventArgs e)
   {
       EventHandler handler = Finished;
       if( handler != null )
       {
           handler(this, e);
       }
   }
}

(请注意,您可能应该更改这些方法,以检查是否必须调用事件处理程序).

(Note that you should probably change those methods, in order to check whether you have to Invoke the eventhandler or not).

然后,在继承自该基类的类中,您只需调用 OnFinished 或 OnLoading 方法即可引发事件:

Then, in classes that inherit from this base class, you can just call the OnFinished or OnLoading methods to raise the events:

public AnotherClass : MyClass
{
    public void DoSomeStuff()
    {
        ...
        OnLoading(EventArgs.Empty);
        ...
        OnFinished(EventArgs.Empty);
    }
}

这篇关于C#:引发继承的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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