If have the following:
public static void main() {
MyClass1 obj = new MyClass1();
obj.Method1();
}
public class MyClass1() {
public void Method1() {
MyClass2 obj = new MyClass2();
obj.Method1();
}
}
public class MyClass2() {
public void Method1() {
MyClass3 obj = new MyClass3();
obj.Method1();
}
}
public class MyClass3() {
public void Method1() {
// Raise event here that is handled in MyClass1?
}
}
Can MyClass3.Method1()
raise an event that is handled in MyClass1
?
How would the event handling code be written if I wanted to acheive this?
Yes it can, but since each level doesn't know about the deeper levels of you chain, you would have to create events on each class. Some like this:
public static void main() {
MyClass1 obj = new MyClass1();
obj.MyEvent += (s, e) => { Console.WriteLine("Fired!"); };
obj.Method1();
}
public class MyClass1 {
public void Method1() {
MyClass2 obj = new MyClass2();
obj.MyEvent += (s, e) => { OnMyEvent(); };
obj.Method1();
}
public event EventHandler MyEvent;
private void OnMyEvent() {
var myEvent = MyEvent;
if (myEvent != null)
myEvent(this, EventArgs.Empty);
}
}
public class MyClass2 {
public void Method1() {
MyClass3 obj = new MyClass3();
obj.MyEvent += (s, e) => { OnMyEvent(); };
obj.Method1();
}
public event EventHandler MyEvent;
private void OnMyEvent() {
var myEvent = MyEvent;
if (myEvent != null)
myEvent(this, EventArgs.Empty);
}
}
public class MyClass3 {
public void Method1() {
// Raise event here that is handled in MyClass1?
OnMyEvent();
}
public event EventHandler MyEvent;
private void OnMyEvent() {
var myEvent = MyEvent;
if (myEvent != null)
myEvent(this, EventArgs.Empty);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With