加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:14:51 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个引用泛型类型数组的类型,而不指定泛型类型.也就是说,我想做相当于Type.GetType(“T []”). 我已经知道如何使用非数组类型执行此操作.例如. Type.GetType("System.Collections.Generic.IEnumerable`1")// ortypeof(IEnumerable) 这是一些重
我正在尝试创建一个引用泛型类型数组的类型,而不指定泛型类型.也就是说,我想做相当于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

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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读