繁体   English   中英

使用反射从静态类获取特定事件的事件处理程序列表

[英]Get list of event handlers of specific event from a static class using reflection

编辑:使用.Net Framework 3.5(Unity3D旧版代码)

外部库中有一个带有静态事件的静态类。 简化为:

internal static class Eventie {

    public delegate void Something();

    public static event Something OnSomething;

}

我需要获取现有的事件处理程序,并从我的代码中调用其中一个。 像这样:

List<Something> delegates = typeOf(Eventie).GetEventHandlersFor(nameof(OnSomething));
delegates.Where(...).ForEach(smth => smth.Invoke()); // pseudo code here

一个适用于非静态的解决方案 ,我成功地将其用于AppDomain.CurrentDomain.AssemblyResolve事件,但它采用了实例参数 ,这使得它无法(afaik)与我得到的静态类一起使用。

解决方案:

// get event field by name
FieldInfo info = typeof(Eventie).GetFields(AllBindings).First(fi => fi.Name == "OnSomething");

// can be null if no event handler delegates added
var eventValue = info.GetValue(null /* static we are */) as Eventie.Something; 

// and here is it; mind the null coalescing - can be null too
Eventie.Something[] invocations = eventValue?.GetInvocationList().Cast<Eventie.Something>().ToArray();

删除事件处理程序:

EventInfo ei = typeof(Eventie).GetEvent(nameof(Eventie.OnSomething));
ei.RemoveEventHandler(null, invocations[i]); // where i is an index

暂无
暂无

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

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