首页 > 其他 > 详细

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

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

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!