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

本文介绍了一个通用的反射工具类,该工具类可以用于将不同类型的数据源(如对象或DataRow)转换为指定类型T的实例。通过使用此工具类,可以简化从数据源到对象模型的映射过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/s-xy/p/6029710.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值