You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法访问目标类类型、无法强转时如何获取类指定成员属性?

解决方案

方案1:反射实现(推荐,稳定性更高)

你可以直接通过反射读取实例的属性值,不需要提前引用对应命名空间,代码示例如下:

// 替换为你实际拿到的object类型的Properties实例
object propertiesInstance = GetYourPropertiesInstance();

Type instanceType = propertiesInstance.GetType();
// 注意字符串中的属性名要和实际定义的大小写完全匹配,如果是字段请改用GetField方法
var uselessProperty = instanceType.GetProperty("useless", 
    System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

if (uselessProperty != null)
{
    double uselessValue = (double)uselessProperty.GetValue(propertiesInstance);
    // 后续直接使用uselessValue即可
}

如果useless是公开字段而非属性,把GetProperty替换为GetField即可。

方案2:dynamic关键字实现(代码更简洁)

如果你可以确定目标类型的结构不会发生变动,可以用dynamic跳过编译时类型检查,代码更简短:

// 替换为你实际拿到的object类型的Properties实例
object propertiesInstance = GetYourPropertiesInstance();
dynamic dynamicInstance = propertiesInstance;
double uselessValue = dynamicInstance.useless;

注意:该方案没有编译时校验,如果类型结构变动、属性名拼写错误,只会在运行时抛出异常。

注意事项

  • 两种方案都需要保证属性/字段名的大小写和实际定义完全一致
  • 反射方案可以通过空判断兼容结构变动的场景,更适合生产环境使用

内容的提问来源于stack exchange,提问作者user4367090

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 09:48:02