using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace JavaCode.cs
{
public class ModelHandler
{
///
/// 填充对象列表
///
public static List FillModel(DataTable dt) where T : new()
{
if (dt == null || dt.Rows.Count == 0)
{
return null;
}
List list = new List();
BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
PropertyInfo[] pis = typeof(T).GetProperties();
foreach (DataRow dr in dt.Rows)
{
T t = new T();
foreach (PropertyInfo pi in pis)
{
object val = dr[pi.Name] == DBNull.Value ? null : dr[pi.Name];
t.GetType().GetProperty(pi.Name, flag).SetValue(t, val, null);
}
list.Add(t);
}
return list;
}
///
/// 填充DataTable
///
public static DataTable FillDataTable(List list) where T : new()
{
if (list == null || list.Count == 0)
{
return null;
}
DataTable dt = CreateDataTable();
PropertyInfo[] pis = typeof(T).GetProperties();
foreach (T t in list)
{
DataRow dr = dt.NewRow();
foreach (PropertyInfo pi in pis)
{
dr[pi.Name] = pi.GetValue(t, null);
}
}
return dt;
}
///
/// 创建DataTable
///
public static DataTable CreateDataTable() where T : new()
{
DataTable dt = new DataTable(typeof(T).Name);
PropertyInfo[] pis = typeof(T).GetProperties();
foreach (PropertyInfo pi in pis)
{
dt.Columns.Add(new DataColumn(pi.Name, pi.PropertyType));
}
return dt;
}
}
}