C# 类型转换 Dictionary转Model类

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-1 18:12   11   0
/// <summary>
        /// 把Model转换为DataRow
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mod"></param>
        /// <returns></returns>
        public static T ParseDictionaryToModel<T>(Dictionary<string, string> dict)
        {
            //
            T obj = default(T);
            obj = Activator.CreateInstance<T>();

            //根据Key值设定 Columns
            foreach (KeyValuePair<string, string> item in dict)
            {
                PropertyInfo prop = obj.GetType().GetProperty(item.Key);
                if(!string.IsNullOrEmpty(item.Value))
                {
                    object value = item.Value;
                    //Nullable 获取Model类字段的真实类型
                    Type itemType = Nullable.GetUnderlyingType(prop.PropertyType) == null ? prop.PropertyType : Nullable.GetUnderlyingType(prop.PropertyType);
                    //根据Model类字段的真实类型进行转换
                    prop.SetValue(obj, Convert.ChangeType(value, itemType), null);
                }
                
                
            }
            return obj;
        }

  

posted on 2016-02-17 13:39 飘扬De黑夜 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/volts0302/p/5195086.html

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP