简体   繁体   English

如何将事件处理程序添加到泛型类型 T 的静态类事件?

[英]How to add an event handler to a static class event of a generic type T?

This one's a bit esoteric.这个有点深奥。

Consider the following code:考虑以下代码:

class MyObject {
  public static event EventHandler SomeEvent;
}

class Container<T> {
  public Container() {
    T.SomeEvent += OnSomeEvent;   // will not compile
  }
  void OnSomeEvent(object sender, object eventArgs) { }
}

Container<MyObject> foo;

Of course this will not compile, because the compiler doesn't know the type of T at compile time.当然这不会编译,因为编译器在编译时不知道T的类型。 More specifically, it doesn't know for certain that it has the event in question.更具体地说,它不确定它是否有相关事件。

How do I attach an event handler to a static event SomeEvent of template parameter T ?如何将事件处理程序附加到模板参数T静态事件SomeEvent Do I need to do messy reflection?我需要做凌乱的反射吗?

Yes, you would need to use reflection here - and it will be messy.是的,您需要在这里使用反射 - 这会很麻烦。 I would also suggest using Type instead of <T> here, as static class etc can't be used with <T> , which could limit the usage.我还建议在这里使用Type而不是<T> ,因为static class等不能与<T>一起使用,这可能会限制使用。 However, as a general rule: you should actively minimize static events anyway (they're a great way to cause memory leaks, and are hard to isolate), so it might be preferable to use an alternative design altogether.然而,作为一个一般的规则:你应该积极反正尽量减少静态活动(他们是一个伟大的方式导致内存泄漏,很难分离),所以它可能是最好完全使用替代设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM