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

 
 
利用反射给泛型 实例化 和 给泛型属性赋值
public IList Tlist(DataTable dt)
        {
            IList tlist = new List();
            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(); 或者这样也可以实例化
                     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;
        }

你可能感兴趣的:(c# 泛型初始化 和 给泛型属性赋值(笔记))