我已經有一些代碼使用反射來安裝Internet Explorer BHO中的MSHTML對象的.NET事件處理程序,它似乎工作正常。但是,當我嘗試刪除事件處理程序時,我遇到了麻煩。爲什麼EventInfo.RemoveEventHandler拋出NullReferenceException?
這是做什麼用的事件處理程序的安裝和拆卸的代碼如下所示:
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
的電話號碼與InstallEventHandler
的電話號碼相同時,最後一行輸出TargetInvocationException
,內部例外情況爲NullReferenceException
。我無法弄清楚我在這裏做錯了什麼,並且堆棧跟蹤沒有多大幫助。
編輯:我已經遍歷調試器中的代碼,並且沒有任何我直接引用的對象變量爲空。
我也嘗試在InstallHandler方法中調用AddEventHandler
和RemoveEventHandler
,並且該方法正常工作。
堆棧跟蹤如下:
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:
什麼可能會造成這一點,我怎麼能解決這個問題?
我已經完成了調試器中的代碼,並且在調用RemoveEventHandler時handlerDelegate不爲null。我已經更新了這個問題來反映這一點。 – Greg 2008-12-17 15:06:56