通过反射将表中的一行数据转换成某一具体的对象

LINQ + .Net3.0的新赋值方法:

代码
1. using System.Collections.Generic;
2. using System.Data;
3. using System.Linq;
4. using 我的应用程序.业务领域;
5. public class MyExtensions
6. {
7. public List<User> ConvertToUsers(DataTable table)
8. {
9. return table.Rows.OfType<DataRow>().Select(r => new User
10. {
11. LogName = (string)r["用户名"],
12. PasswordMD5 = (byte[])r["密码"],
13. 已经使用流量 = (ulong)r["计费"]
14. }).ToList();
15. }
16. }
普通写法:

代码
1. using System;
2. using System.Data;
3. using System.Reflection;
4. namespace Reflex
5. {
6. public class Fill
7. {
8. public static object DataRowFillObject(DataRow row,Type t)
9. {
10. if (row == null || t == null) return null;
11. object result = null;
12. try
13. {
14. result = Activator.CreateInstance(t);
15. PropertyInfo[] ps = t.GetProperties();
16. FieldInfo[] fs = t.GetFields();
17. foreach (PropertyInfo p in ps)
18. {
19. p.SetValue(result, row[p.Name], null);
20. }
21. foreach (FieldInfo f in fs)
22. {
23. f.SetValue(result, row[f.Name]);
24. }
25. }
26. catch
27. {
28. }
29. return result;
30. }
31. }
32. }

 

posted @ 2010-09-06 09:05  悠冉  阅读(150)  评论(0编辑  收藏  举报