日期:2014-05-20 浏览次数:20922 次
using System.Collections.Generic;
using System.Data;
using System.Linq;
using 我的应用程序.业务领域;
public class MyExtensions
{
public List<User> ConvertToUsers(DataTable table)
{
return table.Rows.OfType<DataRow>().Select(r => new User
{
LogName = (string)r["用户名"],
PasswordMD5 = (byte[])r["密码"],
已经使用流量 = (ulong)r["计费"]
}).ToList();
}
}
------解决方案--------------------
//这个是我自己写的反射方法,用于将表中某一行反射成对象
//看看对你有没有帮助吧
using System;
using System.Data;
using System.Reflection;
namespace Reflex
{
public class Fill
{
public static object DataRowFillObject(DataRow row,Type t)
{
if (row == null || t == null) return null;
object result = null;
try
{
result = Activator.CreateInstance(t);
PropertyInfo[] ps = t.GetProperties();
FieldInfo[] fs = t.GetFields();
foreach (PropertyInfo p in ps)
{
p.SetValue(result, row[p.Name], null);
}
foreach (FieldInfo f in fs)
{
f.SetValue(result, row[f.Name]);
}
}
catch
{
}
return result;
}
}
}
------解决方案--------------------
//刚才一直不能回帖,现在给你回帖了, 帮你解决了,给分吧.
using System;
using System.Data;
using System.Reflection;
using System.Collections.Generic;
namespace Reflex
{
public class Fill
{
public static List<T> DataTableFillObject<T>(DataTable dt)
{
if (dt == null) return null;
List<T> result = new List<T>();
Type type = typeof(T);
foreach (DataRow row in dt.Rows)
{
try
{
T t = Activator.CreateInstance<T>();
PropertyInfo[] ps = type.GetProperties();
FieldInfo[] fs = type.GetFields();
foreach (PropertyInfo p in ps)
{
p.SetValue(t, row[p.Name], null);
}
foreach (FieldInfo f in fs)
{
f.SetValue(t, row[f.Name]);
}
result.Add(t);
}
catch
{
}
}
return result;
}
}
}