本帖最后由 ching126 于 2014-12-29 10:05 编辑
[C#] 纯文本查看 复制代码
public class Users
{
//对应数据库表:Users
//字段:ID、userName
public int ID { get; set; }
public string UserName { get; set; }
private static List<T> TableToEntity<T>(DataTable dt) where T : class,new()
{
Type type = typeof(T);
List<T> list = new List<T>();
foreach (DataRow row in dt.Rows)
{
PropertyInfo[] propertyArray = type.GetProperties();
T entity = new T();
foreach (PropertyInfo pi in propertyArray)
{
if (row[pi.UserName] is Int64)
{
pi.SetValue(entity, Convert.ToInt32(row[pi.UserName]), null);
continue;
}
pi.SetValue(entity, row[pi.UserName], null);
}
list.Add(entity);
}
return list;
}
//调用
//DataTable dt = new DataTable();
//List<User> userList = TableToEntity<User>(dt);
}
这是实例代码具体按照自己的情况自己写代码
|