反射和泛型

来源:互联网 发布:python shape函数 编辑:程序博客网 时间:2024/05/17 19:57

GetGenericTypeDefinition 作用于已构造的类型,获取它的泛型类型定义
MakeGenericType             作用于泛型类型定义,返回一个已构造类型


和普通类型一样,任何特定的类型只有一个Type对象。所以,如果调用两次MakeGenericType,每次都传递相同的类型作为参数,那么返回同一个引用。



public static void PrintTypeParameter<T>(){Console.WriteLine(typeof(T));}void Main(){Type type = typeof(Snippet);//获得泛型方法定义MethodInfo definition = type.GetMethod("PrintTypeParameter");//使用MakeGenericMethod返回一个已构造的泛型方法MethodInfo constructed = definition.MakeGenericMethod(typeof(string));constructed.Invoke(null,null);}