MethodInfo method = typeof(string).GetMethod("Copy"); Type t = method.ReturnType.GetInterface(typeof(IEnumerable<>).Name); if (t != null) Console.WriteLine(t); else Console.WriteLine("The return type is not IEnumerable<T>.");
System.Type 类是反射的中心。 当反射提出请求时,公共语言运行时为已加载的类型创建 Type。 可使用 Type 对象的方法、字段、属性和嵌套类来查找该类型的任何信息。
Type 类派生于 System.Reflection.MemberInfo 抽象类。
获取程序集的 Assembly 对象和模块:
1
Assembly a = typeof(object).Module.Assembly;
Type.GetTypes()
从已加载的程序集获取 Type 对象:
1 2 3 4 5 6 7 8
// Loads an assembly using its file name. Assembly a = Assembly.LoadFrom("MyExe.exe"); // Gets the type names from the assembly. Type[] types2 = a.GetTypes(); foreach (Type t in types2) { Console.WriteLine(t.FullName); }
privatestaticvoidMain(string[] args) { Type t = typeof(System.String); Console.WriteLine("Listing all the public constructors of the {0} type", t); // Constructors. ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance); Console.WriteLine("//Constructors"); PrintMembers(ci);
Console.ReadKey(); }
publicstaticvoidPrintMembers(MemberInfo[] ms) { foreach (MemberInfo m in ms) { Console.WriteLine("{0}{1}", " ", m); } Console.WriteLine(); }
privatestaticvoidMain(string[] args) { // 1,获取表示泛型类型的 Type 实例 Type t = typeof(Dictionary<,>);
// 2, 使用 IsGenericType 属性确定类型是否为泛型, // 然后使用 IsGenericTypeDefinition 属性确定类型是否为泛型类型定义。 Console.WriteLine(" Is this a generic type? {0}", t.IsGenericType); Console.WriteLine(" Is this a generic type definition? {0}", t.IsGenericTypeDefinition);
// 4,使用 IsGenericParameter 属性确定它是类型形参(例如,在泛型类型定义中), // 还是为类型形参指定的类型(例如,在构造类型中) Console.WriteLine(" List {0} type arguments:", typeParameters.Length); foreach (Type tParam in typeParameters) { if (tParam.IsGenericParameter) { DisplayGenericParameter(tParam); } else { Console.WriteLine(" Type argument: {0}", tParam); } } Console.ReadKey(); }
privatestaticvoidDisplayGenericParameter(Type tp) { // 5,表示泛型类型参数的 Type 对象的名称和参数位置。 Console.WriteLine(" Type parameter: {0} position {1}", tp.Name, tp.GenericParameterPosition);
if (sConstraints == GenericParameterAttributes.None) { Console.WriteLine(" No special constraints."); } else { if (GenericParameterAttributes.None != (sConstraints & GenericParameterAttributes.DefaultConstructorConstraint)) { Console.WriteLine(" Must have a parameterless constructor."); } if (GenericParameterAttributes.None != (sConstraints & GenericParameterAttributes.ReferenceTypeConstraint)) { Console.WriteLine(" Must be a reference type."); } if (GenericParameterAttributes.None != (sConstraints & GenericParameterAttributes.NotNullableValueTypeConstraint)) { Console.WriteLine(" Must be a non-nullable value type."); } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Security.Permissions;
namespaceConsoleApp1 { // Define an example interface. publicinterfaceITestArgument { }
// Define an example base class. publicclassTestBase { }
// Define a generic class with one parameter. The parameter // has three constraints: It must inherit TestBase, it must // implement ITestArgument, and it must have a parameterless // constructor. publicclassTest<T> whereT : TestBase, ITestArgument, new() { }
// Define a class that meets the constraints on the type // parameter of class Test. publicclassTestArgument : TestBase, ITestArgument { publicTestArgument() { } }
publicclassExample { // The following method displays information about a generic // type. privatestaticvoidDisplayGenericType(Type t) { Console.WriteLine("\r\n {0}", t); Console.WriteLine(" Is this a generic type? {0}", t.IsGenericType); Console.WriteLine(" Is this a generic type definition? {0}", t.IsGenericTypeDefinition);
// Get the generic type parameters or type arguments. Type[] typeParameters = t.GetGenericArguments();
Console.WriteLine(" List {0} type arguments:", typeParameters.Length); foreach (Type tParam in typeParameters) { if (tParam.IsGenericParameter) { DisplayGenericParameter(tParam); } else { Console.WriteLine(" Type argument: {0}", tParam); } } }
// The following method displays information about a generic // type parameter. Generic type parameters are represented by // instances of System.Type, just like ordinary types. privatestaticvoidDisplayGenericParameter(Type tp) { Console.WriteLine(" Type parameter: {0} position {1}", tp.Name, tp.GenericParameterPosition);
Type classConstraint = null;
foreach (Type iConstraint in tp.GetGenericParameterConstraints()) { if (iConstraint.IsInterface) { Console.WriteLine(" Interface constraint: {0}", iConstraint); } }
if (classConstraint != null) { Console.WriteLine(" Base type constraint: {0}", tp.BaseType); } else Console.WriteLine(" Base type constraint: None");
if (sConstraints == GenericParameterAttributes.None) { Console.WriteLine(" No special constraints."); } else { if (GenericParameterAttributes.None != (sConstraints & GenericParameterAttributes.DefaultConstructorConstraint)) { Console.WriteLine(" Must have a parameterless constructor."); } if (GenericParameterAttributes.None != (sConstraints & GenericParameterAttributes.ReferenceTypeConstraint)) { Console.WriteLine(" Must be a reference type."); } if (GenericParameterAttributes.None != (sConstraints & GenericParameterAttributes.NotNullableValueTypeConstraint)) { Console.WriteLine(" Must be a non-nullable value type."); } } }
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")] publicstaticvoidMain() { // Two ways to get a Type object that represents the generic // type definition of the Dictionary class. // // Use the typeof operator to create the generic type // definition directly. To specify the generic type definition, // omit the type arguments but retain the comma that separates // them. Type d1 = typeof(Dictionary<,>);
// You can also obtain the generic type definition from a // constructed class. In this case, the constructed class // is a dictionary of Example objects, with String keys. Dictionary<string, Example> d2 = new Dictionary<string, Example>(); // Get a Type object that represents the constructed type, // and from that get the generic type definition. The // variables d1 and d4 contain the same type. Type d3 = d2.GetType(); Type d4 = d3.GetGenericTypeDefinition();
// Display information for the generic type definition, and // for the constructed type Dictionary<String, Example>. DisplayGenericType(d1); DisplayGenericType(d2.GetType());
// Construct an array of type arguments to substitute for // the type parameters of the generic Dictionary class. // The array must contain the correct number of types, in // the same order that they appear in the type parameter // list of Dictionary. The key (first type parameter) // is of type string, and the type to be contained in the // dictionary is Example. Type[] typeArgs = { typeof(string), typeof(Example) };
// Construct the type Dictionary<String, Example>. Type constructed = d1.MakeGenericType(typeArgs);
DisplayGenericType(constructed);
object o = Activator.CreateInstance(constructed);
Console.WriteLine("\r\nCompare types obtained by different methods:"); Console.WriteLine(" Are the constructed types equal? {0}", (d2.GetType() == constructed)); Console.WriteLine(" Are the generic definitions equal? {0}", (d1 == constructed.GetGenericTypeDefinition()));
// Demonstrate the DisplayGenericType and // DisplayGenericParameter methods with the Test class // defined above. This shows base, interface, and special // constraints. DisplayGenericType(typeof(Test<>));