gpt4 book ai didi

C# 事件传递/冒泡

转载 作者:太空狗 更新时间:2023-10-30 00:46:52 34 4
gpt4 key购买 nike

我在 class 中订阅了一个 Event。比如

MainStation mainStation = StationFactory.GetMainStation();  
mainStation.FrequencyChanged += new EventArgs(MainStation_FrequencyChanged);

我的 MainStation 类通过调用事件 FrequencyChanged() 在某些情况下引发事件

问题

现在我有一个场景,我必须MainStation 实例化 SubStation,它也是 MainStation 的子类具有一些附加功能和 FrequencyChanged 事件必须作为 MainStation 订阅。考虑以下代码:

public class MainStation
{
public event EventHandler FrequencyChanged;
public static SubStation CreateSubStation()
{
SubStation subStation = new SubStation();
//here I want to pass/bubble FrequencyChanged event to SubStation
subStation.FrequencyChanged = FrequencyChanged; //THIS IS WRONG
}
}

底线
我想触发一个类从另一个类订阅的事件,也冒泡事件

更新
StationFactory 创建 MainStation 并且 MainStation 实例中的 FrequencyChanged 事件设置为第一个代码块中定义的。

最佳答案

如果 FrequencyChanged 不属于 MainStation,而是属于某个 Base,您将不得不链接并公开事件你感兴趣。

public class MainStation : Base
{
public event EventHandler StationFrequencyChanged;

public MainStation()
{
// ...

this.FrequencyChanged += new EventHandler(MainStation_FrequencyChanged);
}

void MainStation_FrequencyChanged(object sender, EventArgs e)
{
if (StationFrequencyChanged != null)
StationFrequencyChanged(sender, e);
}

public void GetEventsFrom(MainStation src)
{
//this is where you assign src events to your object
this.StationFrequencyChanged = src.StationFrequencyChanged;
}

public static SubStation CreateSubStation(MainStation main)
{
SubStation subStation = new SubStation();

//register events
subStation.GetEventsFrom(main);

return subStation;
}
}

public class SubStation : MainStation
{

}

关于C# 事件传递/冒泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2214271/

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