zoukankan      html  css  js  c++  java
  • 当用反射获取一个model,这个model里面字段有nullable的时候,获取字段真实类型

    Using Reflection to Determine whether an Type is Nullable And Get the underlying Type

    /// <summary>
     /// Converts a Generic List into a DataTable
     /// </summary>
     /// <param name="list"></param>
     /// <param name="typ"></param>
     /// <returns></returns>
     private DataTable GetDataTable(IList list, Type typ)
     {
         DataTable dt = new DataTable();
    
         // Get a list of all the properties on the object
         PropertyInfo[] pi = typ.GetProperties();
    
         // Loop through each property, and add it as a column to the datatable
         foreach (PropertyInfo p in pi)
         {
             // The the type of the property
             Type columnType = p.PropertyType;
    
             // We need to check whether the property is NULLABLE
             if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
             {
                 // If it is NULLABLE, then get the underlying type. eg if "Nullable<int>" then this will return just "int"
                 columnType = p.PropertyType.GetGenericArguments()[0];
             }
    
             // Add the column definition to the datatable.
             dt.Columns.Add(new DataColumn(p.Name, columnType));
         }
    
         // For each object in the list, loop through and add the data to the datatable.
         foreach (object obj in list)
         {
             object[] row = new object[pi.Length];
             int i = 0;
    
             foreach (PropertyInfo p in pi)
             {
                 row[i++] = p.GetValue(obj, null);
             }
    
             dt.Rows.Add(row);
         }
    
         return dt;
     }



  • 相关阅读:
    51) 项目管理过程简述
    50) 构建完美Docker镜像
    49) 检查Kubernetes集群是否健康
    48) linux运维简答题
    47) 云架构演变 [ECS4]
    46) ECS弹性伸缩和GRE隧道 [ECS3]
    php单文件上传和多文件上传
    PHP文件处理及高级应用
    PHP八种数据类型+使用实例
    php Session方法实例
  • 原文地址:https://www.cnblogs.com/tongdengquan/p/6090466.html
Copyright © 2011-2022 走看看