我正在尝试创建一个引用泛型类型数组的类型,而不指定泛型类型.也就是说,我想做相当于Type.GetType(“T []”).
我已经知道如何使用非数组类型执行此操作.例如.
- Type.GetType("System.Collections.Generic.IEnumerable`1")
- // or
- typeof(IEnumerable<>)
这是一些重现问题的示例代码.
- using System;
- using System.Collections.Generic;
- public class Program
- {
- public static void SomeFunc<T>(IEnumerable<T> collection) { }
- public static void SomeArrayFunc<T>(T[] collection) { }
- static void Main(string[] args)
- {
- Action<Type> printType = t => Console.WriteLine(t != null ? t.ToString() : "(null)");
- Action<string> printFirstParameterType = methodName =>
- printType(
- typeof(Program).GetMethod(methodName).GetParameters()[0].ParameterType
- );
- printFirstParameterType("SomeFunc");
- printFirstParameterType("SomeArrayFunc");
- var iEnumerableT = Type.GetType("System.Collections.Generic.IEnumerable`1");
- printType(iEnumerableT);
- var iEnumerableTFromTypeof = typeof(IEnumerable<>);
- printType(iEnumerableTFromTypeof);
- var arrayOfT = Type.GetType("T[]");
- printType(arrayOfT); // Prints "(null)"
- // ... not even sure where to start for typeof(T[])
- }
- }
输出是:
- System.Collections.Generic.IEnumerable`1[T]
- T[]
- System.Collections.Generic.IEnumerable`1[T]
- System.Collections.Generic.IEnumerable`1[T]
- (null)
我想纠正最后一个“(null)”.
- var someMethod = someType.GetMethod("MethodName",new[] { typeOfArrayOfT });
- // ... call someMethod.MakeGenericMethod some time later
解决方法
简单:
- var arrayOfT = typeof(IEnumerable<>).GetGenericArguments()[0].MakeArrayType();