代码之家  ›  专栏  ›  技术社区  ›  Michael

如何获取T泛型类型?[复制品]

c#
  •  0
  • Michael  · 技术社区  · 7 年前

    以下是函数的签名:

    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 回复  |  直到 7 年前
        1
  •  3
  •   Selman Genç    7 年前

    你可以使用 typeof 要获取泛型参数的类型,请执行以下操作: typeof(T)

        2
  •  1
  •   Olivier Jacot-Descombes    7 年前

    在类型名和泛型类型参数名上,可以应用 typeof 操作人员

    Type type = typeof(T);
    

    在对象上,可以调用 GetType 方法。

    Type arrayType = array.GetType();
    Type elementType = arrayType.GetElementType();
    

    注意 类型 生成编译时已知的静态类型,其中 获得类型 在运行时生成动态类型。

    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 因为我们要检验二者的相等性 Type 不同的对象。