如果你想避免回调解决方案和每个类中的事件链,你基本上有2个解决方案。
第一个包括将 MyClassX 类型的局部变量转换为字段,即像 Chris Gessler 建议的那样,但完全遵循这种方法并删除局部变量。
public static void main() {
MyClass1 obj = new MyClass1();
obj.c2.c3.SomeEvent += obj_SomeEvent;
obj.Method1();
}
private static void obj_SomeEvent(object sender, EventArgs e)
{
Console.WriteLine("Some event fired");
}
public class MyClass1() {
public MyClass2 c2 = new MyClass2();
public void Method1() {
c2.Method1();
}
}
public class MyClass2() {
public MyClass3 c3 = new MyClass3();
public void Method1() {
c3.Method1();
}
}
public class MyClass3() {
public event EventHandler SomeEvent;
private void OnSomeEvent()
{
if (SomeEvent!= null)
{
SomeEvent(this, new EventArgs());
}
}
public void Method1() {
OnSomeEvent();
}
}
您的另一个选择(但如果可行,这实际上取决于您要尝试做什么,而且我无论如何都不喜欢)是将 MyClass3 中的事件简单地定义为静态:
public static void main() {
MyClass3.SomeEvent += obj_SomeEvent;
MyClass1 obj = new MyClass1();
obj.Method1();
}
private static void obj_SomeEvent(object sender, EventArgs e)
{
Console.WriteLine("Some event fired");
}
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 static event EventHandler SomeEvent;
private void OnSomeEvent(MyClass3 anObj)
{
if (SomeEvent!= null)
{
SomeEvent(anObj, new EventArgs());
}
}
public void Method1() {
OnSomeEvent(this);
}
}