码迷,mamicode.com
首页 > 其他好文 > 详细

数据集合转换成对象集合的反射代码

时间:2016-11-04 13:28:24      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:new t   return   new   ret   exce   entity   .property   val   ring   

/// <summary>
/// 反射工具类
/// </summary>
/// <typeparam name="T"></typeparam>
public class AssemblyEntity<T> where T : class,new()
{
public static T SetEntity(object data)
{
T temp = new T();
Type dataType = data.GetType();
foreach (PropertyInfo p in temp.GetType().GetProperties())
{
try
{
p.SetValue(temp, data.GetType().GetProperty(p.Name).GetValue(data));
//temp.GetType().GetProperty(p.Name).SetValue(temp, dataType.GetProperty(p.Name).GetValue(data, null), null);
}
catch (Exception ex)
{
string s = ex.Message;
}

}

return temp;
}
public static T SetEntity(DataRow row)
{
T temp = new T();
foreach (PropertyInfo p in temp.GetType().GetProperties())
{
try
{
if (p.PropertyType != typeof(string))
{
if (p.PropertyType == typeof(Single))
{
p.SetValue(temp, Convert.ToSingle(row[p.Name]));
}
else if (p.PropertyType == typeof(DateTime))
{
p.SetValue(temp, Convert.ToDateTime(row[p.Name]));
}
else
{
p.SetValue(temp, row[p.Name]);
}
}
else
{
p.SetValue(temp, row[p.Name].ToString());
}
}
catch (Exception ex)
{
string s = ex.Message;
}
}
return temp;
}

public static List<T> SetEntitys(DataTable dt)
{
List<T> temp = new List<T>();
foreach (DataRow dr in dt.Rows)
{
temp.Add(SetEntity(dr));
}
return temp;
}
public static List<T> SetEntitys(DataRow[] rows)
{
List<T> temp = new List<T>();
foreach (DataRow dr in rows)
{
temp.Add(SetEntity(dr));
}
return temp;
}
}

数据集合转换成对象集合的反射代码

标签:new t   return   new   ret   exce   entity   .property   val   ring   

原文地址:http://www.cnblogs.com/s-xy/p/6029710.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!