C#用反射判断一个类型是否是Nullable同时获取它的根类型
2023-09-11 14:21:57 时间
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#代码 天气接口 一分钟搞懂你的博客为什么没人看 看完python这段爬虫代码,java流泪了c#沉默了 图片二进制转换与存入数据库相关 C#7.0--引用返回值和引用局部变量 JS直接调用C#后台方法(ajax调用) Linq To Json SqlServer 递归查询
- 程序猿修仙之路--数据结构之你是否真的懂数组? c#socket TCP同步网络通信 用lambda表达式树替代反射 ASP.NET MVC如何做一个简单的非法登录拦截
- 详解C#泛型(二) 获取C#中方法的执行时间及其代码注入 详解C#泛型(一) 详解C#委托和事件(二) 详解C#特性和反射(四) 记一次.net core调用SOAP接口遇到的问题 C# WebRequest.Create 锚点“#”字符问题 根据内容来产生一个二维码
- XML序列化 判断是否是手机 字符操作普通帮助类 验证数据帮助类 IO帮助类 c# Lambda操作类封装 C# -- 使用反射(Reflect)获取dll文件中的类型并调用方法 C# -- 文件的压缩与解压(GZipStream)
- C# DateTime的11种构造函数 [Abp 源码分析]十五、自动审计记录 .Net 登陆的时候添加验证码 使用Topshelf开发Windows服务、记录日志 日常杂记——C#验证码 c#_生成图片式验证码 C# 利用SharpZipLib生成压缩包 Sql2012如何将远程服务器数据库及表、表结构、表数据导入本地数据库
- 利用反射快速给Model实体赋值 使用 Task 简化异步编程 Guid ToString 格式知多少?(GUID 格式) Parallel Programming-实现并行操作的流水线(生产者、消费者) c# 无损高质量压缩图片代码 8种主要排序算法的C#实现 (一) 8种主要排序算法的C#实现 (二)
- 常量,字段,构造方法 调试 ms 源代码 一个C#二维码图片识别的Demo 近期ASP.NET问题汇总及对应的解决办法 c# chart控件柱状图,改变柱子宽度 使用C#创建Windows服务 C#服务端判断客户端socket是否已断开的方法 线程 线程池 Task .NET 单元测试的利剑——模拟框架Moq
- 史上最全的CSS hack方式一览 jQuery 图片轮播的代码分离 JQuery中的动画 C#中Trim()、TrimStart()、TrimEnd()的用法 marquee 标签的使用详情 js鼠标事件 js添加遮罩层 页面上通过地址栏传值时出现乱码的两种解决方法 ref和out的区别在c#中 总结
- C#字符串数组排序 C#排序算法大全 C#字符串比较方法 一个.NET通用JSON解析/构建类的实现(c#) C#处理Json文件 asp.net使用Jquery+iframe传值问题
- 装饰者模式的学习(c#) EF SaveChanges() 报错(转载) C# 四舍五入 保留两位小数(转载) DataGridView样式生成器使用说明 MSSQL如何将查询结果拼接成字符串 快递查询 C# 通过smtp直接发送邮件 C# 带参访问接口,WebClient方式 C# 发送手机短信 文件 日志 写入 与读取
- 浅谈c#的三个高级参数ref out 和Params C#中is与as的区别分析 “登陆”与“登录”有何区别 经典SQL语句大全(绝对的经典)
- C#使用反射获取对象变化的情况
- 浅谈JS中的!=、== 、!==、===的用法和区别 JS中Null与Undefined的区别 读取XML文件 获取路径的方式 C#中Cookie,Session,Application的用法与区别? c#反射 抽象工厂
- c#运用反射获取属性和设置属性值
- c# Linq操作DataTable
- C#实现栈和队列
- 汇川AM402、H3U和上位机C#ModebusTcp通讯
- C#用dynamic一行代码实现反射操作
- C#winform使用进度条
- [C#] Direct2D 学习笔记 (一)vb.net转换为c#
- C#-遍历datatable的几种方法
- c# 析构函数
- C++调用C#库简单例程
- C#-通过反射对可空类型动态赋值的问题
- C# Assembly 反射
- C#与.NET Framework c#编程语言,和java是一样的。(c#,java) -->javaweb,asp.net