用反射写自己的DataTable转为对应的Mod

之前写过类似的方法,今天做项目的时候又遇到了,以前的代码没有保存,导致又得重新写

 

场景:当我们定义自己的很多模型(Mods)的时候,而数据库读取出来的却是DataSet,DataTable类型的时候,我们想在界面上绑定控件的时候需要

将DataTable转为Mods

 

下面是我的代码,switch里面的类型判断可能不是很详细,具体的需要手动修改,加上异常,我这边测试只做了抛出....

 

/// <summary>
/// 模型帮助类
/// 主要功能:实现DataTable与Modle之间的互相转换
/// Created by zwm 2015-11-19
/// </summary>
public class ModHelper
{
/// <summary>
/// 将DataTable类型转为List<T>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> DataTabelToList<T>(DataTable dt)
{
List<T> list=new List<T>();
try
{
if (dt == null || dt.Rows.Count <= 0)
return null;

Type type = typeof(T);
System.Reflection.PropertyInfo[] properties = type.GetProperties();
for (int i = 0; i < dt.Rows.Count;i++ )
{
object obj = type.Assembly.CreateInstance(type.FullName);
foreach (System.Reflection.PropertyInfo property in properties)
{
if (dt.Columns.Contains(property.Name))//存在该列
{

if (dt.Rows[i][property.Name] == null || string.IsNullOrWhiteSpace(dt.Rows[i][property.Name].ToString()))
{
continue;
}


switch (property.PropertyType.Name)
{
case "String":
property.SetValue(obj, dt.Rows[i][property.Name].ToString());
break;
case "Int16":
property.SetValue(obj, Convert.ToInt16(dt.Rows[i][property.Name]));
break;
case "Int32":
property.SetValue(obj, Convert.ToInt32(dt.Rows[i][property.Name]));
break;
case "Int64":
property.SetValue(obj, Convert.ToInt32(dt.Rows[i][property.Name]));
break;
case "bool":
property.SetValue(obj, Convert.ToBoolean(dt.Rows[i][property.Name]));
break;
case "Decimal":
property.SetValue(obj, Convert.ToDecimal(dt.Rows[i][property.Name]));
break;
case "DateTime" :

property.SetValue(obj, Convert.ToDateTime(dt.Rows[i][property.Name]));
break;
default: //有些类型需要转换
Yinoer.YnCommon.Debug.WriteException(new Exception("模型转换的时候-有些类型可能需要转换!"));
break;

}
}
}
list.Add((T)obj);
}
return list;
}
catch (Exception ex)
{
throw ex;//测试的时候用来抛出异常
}
}

转载于:https://www.cnblogs.com/StrongZhang/p/4979105.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值