读书人

反射 泛型解决方法

发布时间: 2012-01-02 22:40:04 作者: rapoo

反射 泛型
public static object FillList(DataTable table, object obj)
{
Type myType = obj.GetType();
List<myType> list = new List<myType>();
myType instance = new myType();
list.Add(instance);
}//报错 不行

我想传进来一个table数据 然后返回一个强类型的泛型 比如

List<MyClass> list=FillList(table,myClass); //myClass是我定义的实体层

不知道可不可以
怎么做??;

[解决办法]
一般来说(主要是因为对“性能”有很大怀疑),会稍微多花1分钟时间写成明确的转换代码,例如:

C# code
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();    }}
[解决办法]
C# code
//这个是我自己写的反射方法,用于将表中某一行反射成对象//看看对你有没有帮助吧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;        }    }}
[解决办法]
C# code
//刚才一直不能回帖,现在给你回帖了, 帮你解决了,给分吧.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;        }    }} 

读书人网 >C#

热点推荐