C# 将对象属性字典集合转换为动态对象并给动态对象动态添加属性

定义将字典集合Dictionary转换为动态对象的方法

        #region 将字典集合转换为动态对象
        /// <summary>
        /// 将字典集合转换为动态对象
        /// </summary>
        /// <param name="propertyDics">属性/属性值字典集合</param>
        /// <returns></returns>
        public static dynamic DictionaryToExpandoObject(IDictionary<string, object> propertyDics)
        {
            if (propertyDics == null) return null;

            IDictionary<string, object> expandoObject = new ExpandoObject();
            foreach (var d in propertyDics)
            {
                expandoObject.Add(d);
            }

            return expandoObject as ExpandoObject;
        }
        #endregion

测试代码:

        #region 测试将字典集合转换为动态对象
        public static void DictionaryToExpandoObject()
        {
            var props = new Dictionary<string, object>();
            props.Add("p1", "p1_Val");
            props.Add("p2", 10);
            var dynamicObj = HttpClientHelper.DictionaryToExpandoObject(props);
            Console.WriteLine($"读取动态对象属性:p1:{dynamicObj.p1},p2:{dynamicObj.p2}");

            // 添加属性
            dynamicObj.p3 = "p3_val";
            // 更新属性
            dynamicObj.p2 = "p2_newVal";

            Console.WriteLine($"读取动态对象属性:p1:{dynamicObj.p1},p2:{dynamicObj.p2},p3:{dynamicObj.p3}");
            Console.Read();
        }
        #endregion

运行结果:

 

posted @ 2021-02-01 20:03  温故纳新  阅读(1734)  评论(0编辑  收藏  举报