获取T数组的类型,而不指定T - Type.GetType("T []")

Mer*_*ham 6 c# generics reflection

我正在尝试创建一个引用泛型类型数组的类型,而不指定泛型类型.也就是说,我想做相当于Type.GetType("T[]").

我已经知道如何使用非数组类型执行此操作.例如

Type.GetType("System.Collections.Generic.IEnumerable`1")
// or
typeof(IEnumerable<>)
Run Code Online (Sandbox Code Playgroud)

这是一些重现问题的示例代码.

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[])
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

System.Collections.Generic.IEnumerable`1[T]
T[]
System.Collections.Generic.IEnumerable`1[T]
System.Collections.Generic.IEnumerable`1[T]
(null)
Run Code Online (Sandbox Code Playgroud)

我想纠正最后一个"(null)".

这将通过指定方法签名用于通过反射获取函数的重载:

var someMethod = someType.GetMethod("MethodName", new[] { typeOfArrayOfT });
// ... call someMethod.MakeGenericMethod some time later
Run Code Online (Sandbox Code Playgroud)

我已经通过过滤结果来获取我的代码GetMethods(),所以这更像是一种知识和理解的练习.

Eni*_*ity 8

简单:

var arrayOfT = typeof(IEnumerable<>).GetGenericArguments()[0].MakeArrayType();
Run Code Online (Sandbox Code Playgroud)