如何获得T泛型的类型?

时间:2018-07-28 14:32:28

标签: c#

以下是函数的签名:

public static T[] Shuffle<T>(T[] array)

在函数中我要检查类型:

var t = T.GetType();

但是我得到这个错误:

'T' is a type parameter, which is not valid in the given context

知道为什么我会出错以及如何获得T类型吗?

2 个答案:

答案 0 :(得分:3)

您可以使用typeof来获取通用参数的类型:typeof(T)

答案 1 :(得分:1)

在类型名称和通用类型参数名称上,您可以应用id status A PA B PPA C PPP 运算符

typeof

在对象上,您可以调用Type type = typeof(T); 方法。

GetType

请注意,Type arrayType = array.GetType(); Type elementType = arrayType.GetElementType(); 会产生在编译时已知的静态类型,而typeof会在运行时产生动态类型。

GetType

由于object obj = new Person(); Type staticType = typeof(object); // ==> System.Object Type runtimeType = obj.GetType(); // ==> Person 产生类型为typeof(T)的对象,因此您可以使用以下命令测试类型

System.Type

typeof(T) == typeof(Person)

但是这两个比较不相等。如果有

T is Person

并假设class Student : Person { } 的类型为T,则

Student

第一次比较产生typeof(T) == typeof(Person) ===> false, because it is typeof(Student) T is Person ===> true, because every type inheriting Person is a Person ,因为我们测试两个false不同的对象是否相等。

相关问题