c# – 获取T数组的类型,而不指定T – Type.GetType(“T []”)

前端之家收集整理的这篇文章主要介绍了c# – 获取T数组的类型,而不指定T – Type.GetType(“T []”)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个引用泛型类型数组的类型,而不指定泛型类型.也就是说,我想做相当于Type.GetType(“T []”).

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

  1. Type.GetType("System.Collections.Generic.IEnumerable`1")
  2. // or
  3. typeof(IEnumerable<>)

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

  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class Program
  5. {
  6. public static void SomeFunc<T>(IEnumerable<T> collection) { }
  7.  
  8. public static void SomeArrayFunc<T>(T[] collection) { }
  9.  
  10. static void Main(string[] args)
  11. {
  12. Action<Type> printType = t => Console.WriteLine(t != null ? t.ToString() : "(null)");
  13. Action<string> printFirstParameterType = methodName =>
  14. printType(
  15. typeof(Program).GetMethod(methodName).GetParameters()[0].ParameterType
  16. );
  17.  
  18. printFirstParameterType("SomeFunc");
  19. printFirstParameterType("SomeArrayFunc");
  20.  
  21. var iEnumerableT = Type.GetType("System.Collections.Generic.IEnumerable`1");
  22. printType(iEnumerableT);
  23.  
  24. var iEnumerableTFromTypeof = typeof(IEnumerable<>);
  25. printType(iEnumerableTFromTypeof);
  26.  
  27. var arrayOfT = Type.GetType("T[]");
  28. printType(arrayOfT); // Prints "(null)"
  29.  
  30. // ... not even sure where to start for typeof(T[])
  31. }
  32. }

输出是:

  1. System.Collections.Generic.IEnumerable`1[T]
  2. T[]
  3. System.Collections.Generic.IEnumerable`1[T]
  4. System.Collections.Generic.IEnumerable`1[T]
  5. (null)

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

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

  1. var someMethod = someType.GetMethod("MethodName",new[] { typeOfArrayOfT });
  2. // ... call someMethod.MakeGenericMethod some time later

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

解决方法

简单:
  1. var arrayOfT = typeof(IEnumerable<>).GetGenericArguments()[0].MakeArrayType();

猜你在找的C#相关文章