无法访问目标类类型、无法强转时如何获取类指定成员属性?
解决方案
方案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
相关产品推荐
相关产品推荐

