C # Event Passing / Bubble Up

I subscribe to Event inside a class . For instance,

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

My MainStation class MainStation event under some condition, just by calling the FrequencyChanged() event

Problem

Now I have a script in which I have to create a SubStation from MainStation , which is also a subclass of MainStation with some additional features, and the FrequencyChanged event should be signed as MainStation subscripted. Consider the code below:

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

Bottom line
I want to fire an event that a class subscribes from another class, also call events

Update
StationFactory creates a MainStation , and the FrequencyChanged event on the MainStation instance is set as defined in the first block of code.

+4
source share
3 answers

If FrequencyChanged does not apply to MainStation , but rather to some Base , you will need to chain and set up the event you are interested in.

 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 { } 
+7
source

If you need something more flexible, you can use WPF RoutedEvents.

Or implement a similar approach manually: organize the objects in a tree and write an event dispatcher that can route events up from the node tree. If the tree hierarchy meets your needs, it will be more convenient and predictable than sending each individual event to a handler.

0
source

If your CreateSubStation method was not static, then the code you have will work as expected. (Provided that the event handlers on MainStation were configured before you created the substation ... this is not a very good design, IMO.)

0
source

Source: https://habr.com/ru/post/1300512/


All Articles