C#:提高继承的事件 [英] C#: Raising an inherited event

查看:107
本文介绍了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.

我收到以下错误:

I receive the following error:

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

我假设我无法访问这些事件同其他继承的成员?

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

推荐答案

您所要做的,是这样的:

What you have to do , is this:

在你的基类(如您已声明的事件),创建保护方法,可用于提高事件:

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天全站免登陆