zoukankan      html  css  js  c++  java
  • C# 类型转换 Dictionary转Model类

    /// <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;
            }
    

      

  • 相关阅读:
    linux 进程间通信之pipe
    makefile详解
    makefile基础
    std::list 源代码解析
    各类编译器 allocator 底层
    oop &&GP 模板 ---> 特化和偏特化
    STL Allocator
    关联式容器
    vector::erase
    maven
  • 原文地址:https://www.cnblogs.com/volts0302/p/5195086.html
Copyright © 2011-2022 走看看