如何从抽象基类访问子类属性?遇运行时错误求解决
问题解决:获取继承类属性值时的"Object does not match target"错误
错误原因
核心问题是没区分静态属性和实例属性的调用规则:
- 静态属性属于类本身,调用
PropertyInfo.GetValue()时需传入null(或类型对象); - 实例属性属于对象实例,调用时必须传入当前实例(
this)。
之前的两种写法只适配了一种属性类型,混合场景下必然触发类型不匹配错误。
修正后的代码
public string Get() { var retBuilder = new StringBuilder(); var currentType = GetType(); // 指定绑定标志,确保获取所有公开的实例/静态属性 var properties = currentType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); foreach (PropertyInfo prop in properties) { object propValue; if (prop.GetGetMethod().IsStatic) { // 静态属性传入null propValue = prop.GetValue(null); } else { // 实例属性传入当前实例 propValue = prop.GetValue(this); } // 处理null值,避免空引用 retBuilder.Append($"{prop.Name}`{(propValue ?? "null")}~"); } return retBuilder.ToString().TrimEnd('~'); }
额外优化点
- 使用
StringBuilder替代字符串拼接,避免频繁生成新字符串,提升性能; - 显式指定
BindingFlags,精准控制要获取的属性范围; - 增加
null值处理,防止属性值为null时引发异常。
内容的提问来源于stack exchange,提问作者JBryanB
相关产品推荐
相关产品推荐

