在开发微信小程序的API获取多条数据时,会遇到返回DataTable对象的数据,但前端无法接收这个类型的数据,需要转化为List数组对象。由此,需要参考网络上的各类资料,编写了一个泛型的方法,具体代码如下:
/// <summary>
/// 将Table数据转换为List模型集合
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static IList<T> TableToListModel<T>(DataTable dt)
where T : new()
{
IList<T> ts = new List<T>();// 定义集合
Type type = typeof(T); // 获得此模型的类型
foreach (DataRow dr in dt.Rows)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
foreach (PropertyInfo pi in propertys)
{
//获取属性名称
String name = pi.Name;
if (dr.Table.Columns.Contains(name))
{
//非泛型
if (!pi.PropertyType.IsGenericType)
{
pi.SetValue(t, string.IsNullOrEmpty(dr[name].ToString()) ? null : Convert.ChangeType(dr[name], pi.PropertyType), null);
}
//泛型Nullable<>
else
{
Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition();
//model属性是可为null类型,进行赋null值
if (genericTypeDefinition == typeof(Nullable<>))
{
//返回指定可以为 null 的类型的基础类型参数
pi.SetValue(t, string.IsNullOrEmpty(dr[name].ToString()) ? null : Convert.ChangeType(dr[name], Nullable.GetUnderlyingType(pi.PropertyType)), null);
}
}
}
}
ts.Add(t);
}
return ts;
}
参考文章:[C#] DataTable转成List集合,只是这篇文章中的以下代码,无法将bigint类型的字段转化为string类型,亲测。
然后,int类型转string同理,未测。
if (value != DBNull.Value)
pi.SetValue(t, value, null);
欢迎指正。