C# DataTable转实体 通用方法

public static T GetEntity<T>(DataTable table) where T : new()
{
T entity = new T();
foreach (DataRow row in table.Rows)
{
foreach (var item in entity.GetType().GetProperties())
{
if (row.Table.Columns.Contains(item.Name))
{
if (DBNull.Value != row[item.Name])
{
item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
} }
}
} return entity;
} public static IList<T> GetEntities<T>(DataTable table) where T : new()
{
IList<T> entities = new List<T>();
foreach (DataRow row in table.Rows)
{
T entity = new T();
foreach (var item in entity.GetType().GetProperties())
{
item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
}
entities.Add(entity);
}
return entities;
}
上一篇:java代码声明引用变量经验


下一篇:c#问答篇:对象与引用变量-----初学者的困惑