使用C#反射解析数据类层级时如何识别隐藏成员?
问题描述
我为脚本引擎编写了一款数据解析器,采用C#反射(Reflection)获取程序实际数据类的值。当前遇到子类隐藏父类成员的类层级结构,C#的运行时绑定器(runtime binder)可正确处理该情况,不会识别被隐藏的成员,但我的解析逻辑无法区分隐藏成员与有效成员。
从示例代码的输出可见,原PSR类的timestamp成员与更新后PSR类的timeStamp(大小写不同)成员均被识别到。我正在寻找可用于判断成员是否隐藏或可访问的属性或方法。
示例代码
using System; using System.Reflection; namespace test { static class PRD { public static dynamic prdData { get; private set; } = new PRD_P20(); } public abstract class PRD_DATA { public BLE ble = new BLE(); public class BLE : PRD_BLE_BASE { } } public abstract class PRD_BLE_BASE { public PSR psr = new PSR(); } public class PSR { public string timestamp = "original"; } public class PRD_P20 : PRD_DATA { /* 实例化新版本BLE并隐藏父类成员 */ public new BLE ble = new BLE(); public new class BLE { public PSR psr = new PSR(); } public class PSR { public string timeStamp = "updated"; } } class Program { static void Main(string[] args) { var o = PRD.prdData; foreach (FieldInfo f in o.GetType().GetFields()) { Console.WriteLine(f.Name + " " + f.DeclaringType); object o1 = f.GetValue(o); foreach (FieldInfo f1 in o1.GetType().GetFields()) { Console.WriteLine("----" + f1.Name); object o2 = f1.GetValue(o1); foreach (FieldInfo f2 in o2.GetType().GetFields()) { Console.WriteLine("--------" + f2.Name + ": " + f2.GetValue(o2)); } } } Console.WriteLine(PRD.prdData.ble.psr.timestamp); // 抛出RuntimeBinderException Console.WriteLine(PRD.prdData.ble.psr.timeStamp); Console.ReadKey(); } } }
输出结果
ble test.PRD_P20 ----psr --------timeStamp: updated ble test.PRD_DATA ----psr --------timestamp: original
内容的提问来源于stack exchange,提问作者Digilee
相关产品推荐
相关产品推荐

