Leer en inglés

Compartir a través de


Type.IsGenericType Propiedad

Definición

Obtiene un valor que indica si el tipo actual es genérico.

C#
public virtual bool IsGenericType { get; }

Valor de propiedad

true si el tipo actual es un tipo genérico; de lo contrario, false.

Ejemplos

En el ejemplo de código siguiente se muestra el valor de las IsGenericTypepropiedades , IsGenericTypeDefinition, IsGenericParametery ContainsGenericParameters para los tipos descritos en la sección Comentarios. Para obtener explicaciones de los valores de propiedad, vea la tabla adjunta en Comentarios.

C#
using System;
using System.Reflection;

public class Base<T, U> {}

public class Derived<V> : Base<string, V>
{
    public G<Derived <V>> F;

    public class Nested {}
}

public class G<T> {}

class Example
{
    public static void Main()
    {
        // Get the generic type definition for Derived, and the base
        // type for Derived.
        //
        Type tDerived = typeof(Derived<>);
        Type tDerivedBase = tDerived.BaseType;

        // Declare an array of Derived<int>, and get its type.
        //
        Derived<int>[] d = new Derived<int>[0];
        Type tDerivedArray = d.GetType();

        // Get a generic type parameter, the type of a field, and a
        // type that is nested in Derived. Notice that in order to
        // get the nested type it is necessary to either (1) specify
        // the generic type definition Derived<>, as shown here,
        // or (2) specify a type parameter for Derived.
        //
        Type tT = typeof(Base<,>).GetGenericArguments()[0];
        Type tF = tDerived.GetField("F").FieldType;
        Type tNested = typeof(Derived<>.Nested);

        DisplayGenericType(tDerived, "Derived<V>");
        DisplayGenericType(tDerivedBase, "Base type of Derived<V>");
        DisplayGenericType(tDerivedArray, "Array of Derived<int>");
        DisplayGenericType(tT, "Type parameter T from Base<T>");
        DisplayGenericType(tF, "Field type, G<Derived<V>>");
        DisplayGenericType(tNested, "Nested type in Derived<V>");
    }

    public static void DisplayGenericType(Type t, string caption)
    {
        Console.WriteLine("\n{0}", caption);
        Console.WriteLine("    Type: {0}", t);

        Console.WriteLine("\t            IsGenericType: {0}", 
            t.IsGenericType);
        Console.WriteLine("\t  IsGenericTypeDefinition: {0}", 
            t.IsGenericTypeDefinition);
        Console.WriteLine("\tContainsGenericParameters: {0}", 
            t.ContainsGenericParameters);
        Console.WriteLine("\t       IsGenericParameter: {0}", 
            t.IsGenericParameter);
    }
}

/* This code example produces the following output:

Derived<V>
    Type: Derived`1[V]
                    IsGenericType: True
          IsGenericTypeDefinition: True
        ContainsGenericParameters: True
               IsGenericParameter: False

Base type of Derived<V>
    Type: Base`2[System.String,V]
                    IsGenericType: True
          IsGenericTypeDefinition: False
        ContainsGenericParameters: True
               IsGenericParameter: False

Array of Derived<int>
    Type: Derived`1[System.Int32][]
                    IsGenericType: False
          IsGenericTypeDefinition: False
        ContainsGenericParameters: False
               IsGenericParameter: False

Type parameter T from Base<T>
    Type: T
                    IsGenericType: False
          IsGenericTypeDefinition: False
        ContainsGenericParameters: True
               IsGenericParameter: True

Field type, G<Derived<V>>
    Type: G`1[Derived`1[V]]
                    IsGenericType: True
          IsGenericTypeDefinition: False
        ContainsGenericParameters: True
               IsGenericParameter: False

Nested type in Derived<V>
    Type: Derived`1+Nested[V]
                    IsGenericType: True
          IsGenericTypeDefinition: True
        ContainsGenericParameters: True
               IsGenericParameter: False
 */

Comentarios

Utilice la IsGenericType propiedad para determinar si un Type objeto representa un tipo genérico. Utilice la ContainsGenericParameters propiedad para determinar si un Type objeto representa un tipo construido abierto o un tipo construido cerrado.

Nota

La IsGenericType propiedad devuelve false si el tipo inmediato no es genérico. Por ejemplo, una matriz cuyos elementos son de tipo A<int> (A(Of Integer) en Visual Basic) no es en sí mismo un tipo genérico.

En la tabla siguiente se resumen las condiciones invariables para los términos comunes usados en la reflexión genérica.

Término Invariable
definición de tipo genérico La propiedad IsGenericTypeDefinition es true.

Define un tipo genérico. Un tipo construido se crea llamando al MakeGenericType método en un Type objeto que representa una definición de tipo genérico y especificando una matriz de argumentos de tipo.

MakeGenericType solo se puede llamar a en definiciones de tipo genérico.

Cualquier definición de tipo genérico es un tipo genérico (la IsGenericType propiedad es true), pero el contrario no es true.
tipo genérico La propiedad IsGenericType es true.

Puede ser una definición de tipo genérico, un tipo construido abierto o un tipo construido cerrado.

Tenga en cuenta que un tipo de matriz cuyo tipo de elemento es genérico no es un tipo genérico. Lo mismo sucede con un Type objeto que representa un puntero a un tipo genérico.
tipo construido abierto La propiedad ContainsGenericParameters es true.

Algunos ejemplos son un tipo genérico que tiene parámetros de tipo sin asignar, un tipo anidado en una definición de tipo genérico o en un tipo construido abierto, o un tipo genérico que tiene un argumento de tipo para el que la ContainsGenericParameters propiedad es true.

no es posible crear una instancia de un tipo construido abierto.

Tenga en cuenta que no todos los tipos construidos abiertos son genéricos. Por ejemplo, una matriz cuyo tipo de elemento es una definición de tipo genérico no es genérica y un puntero a un tipo construido abierto no es genérico.
tipo construido cerrado La propiedad ContainsGenericParameters es false.

Cuando se examina de forma recursiva, el tipo no tiene parámetros genéricos sin asignar.
parámetro de tipo genérico La propiedad IsGenericParameter es true.

La propiedad ContainsGenericParameters es true.

En una definición de tipo genérico, un marcador de posición para un tipo que se asignará más adelante.
argumento de tipo genérico Puede ser cualquier tipo, incluido un parámetro de tipo genérico.

Los argumentos de tipo se especifican como una matriz de Type objetos pasados al MakeGenericType método al crear un tipo genérico construido. Si se van a crear instancias del tipo resultante, la ContainsGenericParameters propiedad debe ser false para todos los argumentos de tipo.

En el ejemplo de código siguiente y la tabla se muestran algunos de estos términos e invariables. La Derived clase es de interés particular porque su tipo base es un tipo construido que tiene una combinación de tipos y parámetros de tipo en su lista de argumentos de tipo.

C#
public class Base<T, U> {}

public class Derived<V> : Base<string, V>
{
    public G<Derived <V>> F;

    public class Nested {}
}

public class G<T> {}

En la tabla siguiente se muestran ejemplos que usan y se basan en las clases Base, Derivedy G. Cuando el código de C++ y C# es el mismo, solo se muestra una entrada.

Ejemplo Invariables
Derived(Of V)

Derived<V>
Para este tipo:

IsGenericType es true.

IsGenericTypeDefinition es true.

ContainsGenericParameters es true.
Base(Of String, V)

Base<String,V>

Base<String^,V>
Para este tipo:

IsGenericType es true.

IsGenericTypeDefinition es false.

ContainsGenericParameters es true.
Dim d() As Derived(Of Integer)

Derived<int>[] d;

array<Derived<int>^>^ d;
Para el tipo de variable d:

IsGenericType es false porque d es una matriz.

IsGenericTypeDefinition es false.

ContainsGenericParameters es false.
T, Uy V (en todas partes aparecen) IsGenericParameter es true.

IsGenericType es false porque no hay ninguna manera de restringir un parámetro de tipo a tipos genéricos.

IsGenericTypeDefinition es false.

ContainsGenericParameters es true porque T, Uy V son propios parámetros de tipo genéricos. Esto no implica nada sobre los argumentos de tipo que se les asignan más adelante.
Tipo de campo F IsGenericType es true.

IsGenericTypeDefinition es false porque se ha asignado un tipo al parámetro type de G. Tenga en cuenta que esto equivale a haber llamado al MakeGenericType método .

ContainsGenericParameters es true porque el tipo de campo F tiene un argumento de tipo que es un tipo construido abierto. El tipo construido está abierto porque su argumento de tipo (es decir, Base) es una definición de tipo genérico. Esto ilustra la naturaleza recursiva de la IsGenericType propiedad .
La clase anidada Nested IsGenericType es true, aunque la Nested clase no tenga parámetros de tipo genérico propios, ya que está anidado en un tipo genérico.

IsGenericTypeDefinition es true. Es decir, puede llamar al MakeGenericType método y proporcionar el parámetro type del tipo envolvente, Derived.

ContainsGenericParameters es true porque el tipo envolvente, Derived, tiene parámetros de tipo genérico. Esto ilustra la naturaleza recursiva de la ContainsGenericParameters propiedad .

Se aplica a

Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Consulte también