Я пытаюсь создать тип, который ссылается на массив универсального типа, без указания универсального типа. То есть, Я хотел бы сделать эквивалент 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)
Я бы хотел исправить последний "(ноль)".
Это будет использоваться для получения перегрузки функция через отражения, указав сигнатуру метода:
var someMethod = someType.GetMethod("MethodName", new[] { typeOfArrayOfT });
// ... call someMethod.MakeGenericMethod some time later
Я уже заставил свой код в основном работать, отфильтровав результат GetMethods ()
, так что это скорее упражнение на знание и понимание.