编辑:使用.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
有a solution适用于非静态类,我成功地将其用于干预AppDomain.CurrentDomain.AssemblyResolve
事件,但是它需要一个实例参数这使得(afaik)无法与我得到的静态类一起使用。
答案 0 :(得分:0)
解决方案:
// 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