因此,我立即注意到MSDN引用在其案例列表中两次包含“或”,但是花了我很长时间才意识到原因。现实情况是,存在三种主要情况,这三种情况之一被分为另外三种情况。使用更清晰的标点符号,情况是
通用类型参数;
基于类型参数的数组类型,指针类型或byref类型;要么
不是通用类型定义,但包含未解析的类型参数的通用类型。
我了解第一种情况,Rahul的回答将我定向到了MSDN博客文章,该文章解释并给出了最后一种情况的两个示例,现在我可以给出其余情况的示例。
using System; using System.Linq; namespace ConsoleApplication { public class GenericClass{ public void ArrayMethod(T[] parameter) { } public void ReferenceMethod(ref T parameter) { } } public class AnotherGenericClass : GenericClass { } public static class Program { public static void Main(string[] args) { GenericTypeParameter(); ArrayTypeBasedOnTypeParameter(); PointerTypeBasedOnTypeParameter(); ByRefTypeBasedOnTypeParameter(); NongenericTypeDefinitionWithUnresolvedTypeParameters(); Console.ReadKey(); } public static void GenericTypeParameter() { var type = typeof(GenericClass<>) .GetGenericArguments() .First(); PrintFullName("Generic type parameter", type); } public static void ArrayTypeBasedOnTypeParameter() { var type = typeof(GenericClass<>) .GetMethod("ArrayMethod") .GetParameters() .First() .ParameterType; PrintFullName("Array type based on type parameter", type); } /* * Would like an actual example of a pointer to a generic type, * but this works for now. */ public static void PointerTypeBasedOnTypeParameter() { var type = typeof(GenericClass<>) .GetGenericArguments() .First() .MakePointerType(); PrintFullName("Pointer type based on type parameter", type); } public static void ByrefTypeBasedOnTypeParameter() { var type = typeof(GenericClass<>) .GetMethod("ReferenceMethod") .GetParameters() .First() .ParameterType; PrintFullName("ByRef type based on type parameter", type); } private static void NongenericTypeDefinitionWithUnresolvedTypeParameters() { var type = typeof(AnotherGenericClass<>).BaseType; PrintFullName("Nongeneric type definition with unresolved type parameters", type); } public static void PrintFullName(string name, Type type) { Console.WriteLine(name + ":"); Console.WriteLine("--Name: " + type.Name); Console.WriteLine("--FullName: " + (type.FullName ?? "null")); Console.WriteLine(); } } } /***Output*** Generic type parameter: --Name: T --FullName: null Array type based on type parameter: --Name: T[] --FullName: null Pointer type based on type parameter: --Name: T* --FullName: null Byref type based on type parameter: --Name: T& --FullName: null Nongeneric type definition with unresolved type parameters: --Name: GenericClass`1 --FullName: null ***Output***/