gpt4 book ai didi

C#:引发继承事件

转载 作者:IT王子 更新时间:2023-10-29 03:32:31 25 4
gpt4 key购买 nike

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

public event EventHandler Loading;
public event EventHandler Finished;

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

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

我收到以下错误:

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

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

最佳答案

你要做的,是这样的:

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

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

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

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

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

关于C#:引发继承事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/756237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com