c# 泛型初始化 和 给泛型属性赋值(笔记)

来源:互联网 发布:彩霸王软件 编辑:程序博客网 时间:2024/05/16 08:54
 
 
利用反射给泛型 实例化 和 给泛型属性赋值
public IList<T> Tlist(DataTable dt)        {            IList<T> tlist = new List<T>();            if (dt.Rows.Count > 0)            {                System.Type t = typeof(T);                Assembly ass=Assembly.GetAssembly(t);//获取泛型的程序集                PropertyInfo[] pc = t.GetProperties();//获取到泛型所有属性的集合                foreach (DataRow dr in dt.Rows)                {                    Object _obj =ass.CreateInstance(t.FullName);//泛型实例化                    //Object obj = Activator.CreateInstance<T>(); 或者这样也可以实例化
                     foreach (PropertyInfo pi in pc)                    {                        if (pi.PropertyType.Equals(typeof(String)))//判断属性的类型是不是String                        {                            String _name =pi.Name;                            pi.SetValue((T)_obj, dr[_name].ToString(), null);//给泛型的属性赋值                        }                    }                    tlist.Add((T)_obj);                }            }            return tlist;        }

原创粉丝点击