PropertyInfo.GetProperty returns null 在不应该的时候

PropertyInfo.GetProperty returns null when it shouldn't

我正在尝试获取 WPF WebBrowser 对象的私有 属性 的值。我可以在调试器中看到它有一个非空值。

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 项目 运行。 我尝试 运行 它具有管理员权限(向项目添加清单文件),但没有任何区别。

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 时才使用第二个。