namespace console_泛型类 { class Program { public static void Main(string[] args) { //泛型类封装不特定于特定数据类型的操作。 //第一次看到感觉很抽象,要理解这句话中的 封装 和 操作 两个关键词 //通俗讲就是泛型类就是对不确定数据类型的一些操作和封装 UserInfo<Person> t = new UserInfo<Person>(); t.GetPerproty(); Console.ReadKey(true); } } // 创建个实体类测试 class Person{ public string Name{get{return "hah";}} public string Sex{get; set;} public int Age{get; set;} private int _count; public readonly string Weight; public struct t{} public void test(){Console.WriteLine(this.Name);} public void test2(){} private void Test3(){} protected void test4(){} } class UserInfo<T> where T : new() { public void GetPerproty(){ //实例一个新的操作对象 注意用new 进行限制一个默认无参构造函数 T t = new T(); //获取type Type type = t.GetType(); //获取实体类的属性 Console.WriteLine("==============Properties============="); PropertyInfo[] ps = type.GetProperties(); foreach (PropertyInfo p in ps) { //可以看到只能获取pubulic公开的 readonly也不可以, 确切说应该是至少实现一个访问器的字段 Console.WriteLine("p.Name-{0}, p.canRead-{1}, p.canWrite-{2}", p.Name, p.CanRead, p.CanWrite); } //获取Members,获取所有的方法,属性,接口,结构等等 Console.WriteLine("==============Members============="); MemberInfo[] ms = type.GetMembers(); foreach (MemberInfo m in ms) { Console.WriteLine(m.Name); } Console.WriteLine("==============Methods============="); MethodInfo[] mi = type.GetMethods(); foreach (MethodInfo m in mi) { Console.WriteLine(m.Name); } Console.WriteLine("==============RuntimeMethods============="); IEnumerable<MethodInfo> mm = type.GetRuntimeMethods(); foreach (MethodInfo m in mi) { Console.WriteLine(m.Name); } Console.WriteLine("==============Property SetValue============="); //设置其中一个值 PropertyInfo p1 = type.GetProperty("Name"); Console.WriteLine(p1.Name); MethodInfo m1 = type.GetMethod("test"); m1.Invoke(t, null); } } }