2016-08-26 110 views
2

我想要獲取WPF WebBrowser對象的私有屬性的值。我可以在調試器中看到它有一個非空值。PropertyInfo.GetProperty返回null時,它不應該

PropertyInfo activeXProp = Browser.GetType().GetProperty("ActiveXInstance", BindingFlags.Instance | BindingFlags.NonPublic); 
object activeX = activeXProp.GetValue(Browser, null); // here I get null for the activeX value 
activeX.GetType().GetProperty("Silent").SetValue(activeX, true); // and here it crashes for calling a method on a null reference... 

我的猜測是我沒有以正確的方式使用反射,但是在這種情況下正確的方法是什麼? 該項目是一個運行在.NET 4.6.1和Windows 10上的WPF項目。 我試着用管理員權限運行它(向項目中添加一個清單文件),但沒有任何區別。

+2

你確定'activeX'是'null'嗎?它不會給我null。 –

+0

謝謝你試試看。不幸的是,它確實給了我一個空值。這是完整的項目,如果你想檢查:https://github.com/zskolbay/WpfBrowserTest – Bedford

+0

我在github上測試了你的代碼,'activeX'不爲null。只有下一行引發異常。 –

回答

2

activeX.GetType()返回的類型是System .__ ComObject,它不支持這種反射。但是,有兩個簡單的解決方案。

使用dynamic

dynamic activeX = activeXProp.GetValue(Browser, null); 
activeX.Silent = true; 

dynamic支持所有類型的COM反射的,由的IDispatch COM接口(由所有ActiveX元件來實現)提供。

只是反射

一個小小的改變你的代碼不一樣上面的代碼:

object activeX = activeXProp.GetValue(Browser, null); 
activeX.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, activeX, new object[]{true}); 

兩種方法調用對象的同樣的事情,但我想第一個是由於呼叫站點的高速緩存,隨着時間的推移會更快。只有在出於某種原因不能使用dynamic的情況下才使用第二個。

相關問題