C#高级应用之反射,把实体类数据反射到字典

/// <summary>
        /// 获取警报的端口状态
        ///dictAlarmPort 自定义的字典名
        /// </summary>
        private Dictionary<uint, Dictionary<string, uint>> dictAlarmPort = new Dictionary<uint, Dictionary<string, uint>>();


for (uint i = 1; i <= 4; i++)
            {
                dictAlarmPort[i] = new Dictionary<string, uint>();
            }
            //RongDa  2022.11.21,将端口数据反射到字典中
            Type ts300 = typeof(TS300PortStatusDefine);  //TS300PortStatusDefine是需要转换的类名(反射到字典里,有助于性能提升)
            Type ts480 = typeof(TS480PortStatusDefine);  //TS480PortStatusDefine是需要转换的类名(反射到字典里,有助于性能提升)
            System.Reflection.FieldInfo[] ts300fis = ts300.GetFields();  // 注意,这里不能有任何选项,否则将无法获取到const常量
            System.Reflection.FieldInfo[] ts480fis = ts480.GetFields();
            foreach (var fieldInfo in ts300fis)
            {
                dictAlarmPort[1][fieldInfo.Name] = Convert.ToUInt32(fieldInfo.GetValue(null));
            }

            foreach (var fieldInfo in ts480fis)
            {
                dictAlarmPort[2][fieldInfo.Name] = Convert.ToUInt32(fieldInfo.GetValue(null));
            }

C#高级应用之反射,把实体类数据反射到字典插图

 

这是我在工作中遇到的,比较实用,也是代码比较少,看起来比较简单的。

这里我是一开始就实例化4个字典占位,然后根据需要反射的类,添加到指定的字典里。

因为还是萌新,各方面不成熟。如有更好的办法,欢迎大家向本站长提出!

相关推荐: C#String类用法之String.LastIndexOf 方法

// // 摘要: // 报告指定字符串在此实例中的最后一个匹配项的从零开始的索引的位置。 // // 参数: // value: // 要搜寻的字符串。 // // 返回结果: // 如果找到该字符串,则为 value 的从零开始的起始索引位置;如果未找到该…

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容