将事件路由到类中的事件处理程序的最佳方法是什么,希望无需手动连接它们。
在下面的代码示例中,只需将事件强制转换为dynamic
即可将事件路由到正确的处理程序。
class Program {
static void Main(string[] args) {
var myEvent1 = new MyEvent1() as object;
var myEvent2 = new MyEvent2() as object;
var myObject = new Inherited() as Base;
myObject.On(myEvent1);
myObject.On(myEvent2);
}
}
public class MyEvent1 {
}
public class MyEvent2 {
}
public class Base {
public void On(object @event) {
On((dynamic)@event);
}
public void On(MyEvent1 @event) {
// it works!
}
public void On(MyEvent2 @event) {
// it works!
}
}
public class Inherited : Base {
}
但是,当我将类型化的事件处理程序移动到继承的类时,处理程序不再起作用了:
class Program {
static void Main(string[] args) {
var myEvent1 = new MyEvent1() as object;
var myEvent2 = new MyEvent2() as object;
var myObject = new Inherited() as Base;
myObject.On(myEvent1);
myObject.On(myEvent2);
}
}
public class MyEvent1 {
}
public class MyEvent2 {
}
public class Base {
public void On(object @event) {
On((dynamic)@event);
// stack overflow happens here :(
}
}
public class Inherited : Base {
public void On(MyEvent1 @event) {
// nothing happens :(
}
public void On(MyEvent2 @event) {
// nothing happens :(
}
}
显然,它需要在继承的类中使用处理程序(我必须使用myObject
作为基类的实例),所以我找到了一种更好的方法来路由事件。
答案 0 :(得分:2)
试试这个:
((dynamic)this).On((dynamic)e);