我有一些代码正在使用反射在InternetExplorerBHO中的MSHTML对象上安装.NET事件处理程序,它看起来工作正常。然而,当我试图删除事件处理程序时,我遇到了麻烦。
事件处理程序安装和删除的代码如下所示:
public class HandlerExample {
private static void Handler(IHTMLEventObj e) { ... }
private static Delegate handlerDelegate;
public static void InstallHandler(IHTMLElement target, string eventName)
{
// FindInterface() finds the correct event interface for the particular subclass of
// IHTMLElement that target really is
Type eventInterface = FindInterface(target);
EventInfo eInfo = eventInterface.GetEvent(eventName);
Type tHandler = eInfo.EventHandlerType;
handlerDelegate = Delegate.CreateDelegate(tHandler, typeof(HandlerExample), "Handler");
eInfo.AddEventHandler(target, handlerDelegate);
}
public static void RemoveHandler(IHTMLElement target, string eventName)
{
Type eventInterface = FindInterface(target);
EventInfo eInfo = eventInterface.GetEvent(eventName);
eInfo.RemoveEventHandler(target, handlerDelegate); // THIS LINE CRASHES
}
}
呼唤
InstallEventHandler
很好,而且
Handler
然后在浏览器中触发事件时调用。当我呼唤
RemoveEventHandler
与
安装事件处理程序
呼叫,最后一行抛出
TargetInvocationException
,但内部例外
NullReferenceException
。我不知道我做错了什么,堆栈跟踪也没什么帮助。
编辑:
我已经遍历了调试器中的代码,并且我直接引用的对象变量都不是空的。
我也试过给他们打电话
AddEventHandler
和
RemoveEventhandler公司
在installhandler方法中,这是正确的。
堆栈跟踪如下:
System.Reflection.TargetInvocationException occurred
Message="Exception has been thrown by the target of an invocation."
Source="mscorlib"
StackTrace:
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.EventInfo.RemoveEventHandler(Object target, Delegate handler)
at RemoveHandler(IHTMLElement target, String eventName)
InnerException: System.NullReferenceException
Message="Object reference not set to an instance of an object."
Source="Microsoft.mshtml"
StackTrace:
at mshtml.HTMLTextContainerEvents2_EventProvider.remove_onclick(HTMLTextContainerEvents2_onclickEventHandler )
at mshtml.HTMLTextAreaElementClass.HTMLTextContainerEvents2_Event_remove_onclick(HTMLTextContainerEvents2_onclickEventHandler )
InnerException:
是什么引起的,我该怎么解决?