gpt4 book ai didi

c# - PropertyInfo.GetProperty 在不应返回 null 时返回

转载 作者:行者123 更新时间:2023-11-30 23:21:34 41 4
gpt4 key购买 nike

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

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

最佳答案

activeX.GetType()返回的类型是System.__ComObject,不支持这种反射。但是,有两个简单的解决方案。

使用动态

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

dynamic 支持所有类型的 COM 反射,由 IDispatch COM 接口(interface)(由所有 ActiveX 元素实现)提供。

只是反射(reflection)

对你的代码做一点小改动就可以实现与上面代码相​​同的效果:

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

这两种方法在对象上调用相同的东西,但我猜第一个方法会随着时间的推移更快,因为调用站点的缓存。仅当您出于某种原因无法使用 dynamic 时才使用第二个。

关于c# - PropertyInfo.GetProperty 在不应返回 null 时返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39168112/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com