C#用反射判断一个类型是否是Nullable同时获取它的根类型(转自网络)

在我们的应用程序中我们使用类描述我们的业务对象,为我们产生一些报表之类的,那就依赖大量不同的对象,我们创建一个帮助方法来转换我们的业务对象,或是一个List的业务对象到DataTables.

由于数据库表中字段可为null,对应.net 2.0以后我们可用Nullable类型来实现,那当我们业务对象类中字段有null时,并需要转换为DataTable时,这个场景产生,你可能用到以下方法:

下面的代码是一个list对象(不支持处理复杂类型)返回一个描述对象的DataTable

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

上面的代码的关键点:

  • 用 PropertyType.IsGenericType 决定property是否是generic类型
  • 用 ProprtyType.GetGenericTypeDefinition() == typeof(Nullable<>) 检测它是否是一个nullable类型
  • 用 PropertyType.GetGenericArguments() 获取基类型。

下面让我们来应用一下:

public class Person
{
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
    public DateTime? DateOfDeath { get; set; }
}

public class Example
{
    public static DataTable RunExample()
    {
        Person edward = new Person() { Name = "Edward", DateOfBirth = new DateTime(1900, 1, 1), DateOfDeath = new DateTime(1990, 10, 15) };
        Person margaret = new Person() { Name = "Margaret", DateOfBirth = new DateTime(1950, 2, 9), DateOfDeath = null };
        Person grant = new Person() { Name = "Grant", DateOfBirth = new DateTime(1975, 6, 13), DateOfDeath = null };

        List<Person> people = new List<Person>();

        people.Add(edward);
        people.Add(margaret);
        people.Add(grant);

        DataTable dt = GetDataTable(people, typeof(Person));

        return dt;
    }
}
将返回的DataTable像下面的内容:
Name (string)    DateOfBirth (DateTime)    DateOfDeath (DateTime)
Edward    1/1/1900    15/10/1990
Margaret    9/2/1950    [NULL]
Grant    13/6/1975    [NULL]

C#用反射判断一个类型是否是Nullable同时获取它的根类型(转自网络)

时间: 2024-08-22 09:52:19

C#用反射判断一个类型是否是Nullable同时获取它的根类型(转自网络)的相关文章

Java中如何判断一个double类型的数据为0?

Java中如何判断一个double类型的数据为0 其实这个问题很简单,只是很多时候考虑复杂了,直接用==判断即可.下面给出测试例子: /**  * 如何判断一个double类型的数据为0  *  * @author leizhimin 2014/8/27 10:31  */ public class Test4 {     public static void main(String[] args) {         double x = 0.00000000000000000;       

判断一个变量是否是某种基本类型.

public static void Judge(object ma) { var ta = ma.GetType(); //通过Type可以对传入的参数类型进行基本类型的判断 Console.WriteLine(ta.IsEnum); //枚举 Console.WriteLine(ta.IsValueType); //值类型 Console.WriteLine(ta.IsInterface); //接口 Console.WriteLine(ta.IsClass); //引用类型 Console

判断一个变量是数组类型的方法

在很多时候,我们都需要对一个变量进行数组类型的判断(借鉴) 学过js就应该知道typeof运算符返回字符串,该字符串代表操作数的类型(即返回数据类型)这是最常用的. 下面多种实现方式: JavaScript中检测对象的方法 1.typeof操作符 这种方法对于一些常用的类型来说那算是毫无压力,比如Function.String.Number.Undefined等,但是要是检测Array的对象就不起作用了. alert(typeof null); // "object" alert(ty

jquery ajax中支持哪些返回类型以及js中判断一个类型常用的方法?

1 jquery ajax中支持哪些返回类型在JQuery中,AJAX有三种实现方式:$.ajax() , $.post , $.get(). 预期服务器返回的数据类型.如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断,比如 XML MIME 类型就被识别为 XML.在 1.4 中,JSON 就会生成一个 JavaScript 对象,而 script 则会执行这个脚本.随后服务器端返回的数据会根据这个值解析后,传递给回调 函数.可用值: •"xml": 返回

js中判断一个变量是否为数字类型的疑问

1.typeof(a)=="number" 是true,但是a instanceof Number却为false,不理解 2.isNaN()不能判断一个变量是否为数字类型,isNaN(123)值为false,isNaN('123')值也为false.isNaN() 的实际作用跟它的名字isNaN并不一致,isNaN(NaN)值为true,isNaN(Number("xyz"))值为true,isNaN("abc")值为true,isNaN(123

Javascript如何判断一个变量是数字类型?

isNaN()不能判断一个变量是否为数字类型,isNaN(123)值为false,isNaN('123')值也为false.isNaN() 的实际作用跟它的名字isNaN并不一致,isNaN(NaN)值为true,isNaN(Number("xyz"))值为true,isNaN("abc")值为true,isNaN(123/0)值为false,所以它实际是将不能转换成number类型的其他类型及其自身NaN都判断为true,而除了其自身NaN外所有的number类型

利用反射模拟一个spring的内部工作原理

这个简单的案例是实行了登录和注册的功能,没有链接数据库. 在bean中id 是唯一的,id和name的区别在于id不能用特殊字符而name可以用特殊字符,比如:/-\.... 1 package com.obtk.reflect; 2 3 public class Logon { 4 /** 5 * 帐号密码长度大于六位字符就成功,否则失败! 6 * */ 7 public String select(String name, String pass) { 8 if (name.length()

JavaScript判断一个变量是对象还是数组

typeof都返回object 在JavaScript中所有数据类型严格意义上都是对象,但实际使用中我们还是有类型之分,如果要判断一个变量是数组还是对象使用typeof搞不定,因为它全都返回object 1 2 3 4 5 6 var o = { 'name':'lee' }; var a = ['reg','blue']; document.write( ' o typeof is ' + typeof o); document.write( ' <br />'); document.wri

type,isinstance判断一个变量的数据类型

type,isinstance判断一个变量的数据类型 import types type(x) is types.IntType # 判断是否int 类型 type(x) is types.StringType #是否string类型 ......... -------------------------------------------------------- 超级恶心的模式,不用记住types.StringType import types type(x) == types(1) # 判