Partager via


Type.IsGenericType Propriété

Définition

Obtient une valeur indiquant si le type actuel est un type générique.

public:
 virtual property bool IsGenericType { bool get(); };
public virtual bool IsGenericType { get; }
member this.IsGenericType : bool
Public Overridable ReadOnly Property IsGenericType As Boolean

Valeur de propriété

true si le type actuel est un type générique ; sinon, false.

Exemples

L’exemple de code suivant affiche la valeur des IsGenericTypeIsGenericTypeDefinitionIsGenericParameterContainsGenericParameters types décrits dans la section Notes. Pour obtenir des explications sur les valeurs de propriété, consultez le tableau associé dans Notes.

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
 */
open System

type Base<'T, 'U>() = class end

type G<'T>() = class end

type Derived<'V>() =
    inherit Base<string, 'V>()
    
    [<DefaultValue>]
    val mutable public F : G<Derived<'V>>

let displayGenericType (t: Type) caption =
    printfn $"\n{caption}"
    printfn $"    Type: {t}"

    printfn $"\t            IsGenericType: {t.IsGenericType}" 
    printfn $"\t  IsGenericTypeDefinition: {t.IsGenericTypeDefinition}" 
    printfn $"\tContainsGenericParameters: {t.ContainsGenericParameters}"
    printfn $"\t       IsGenericParameter: {t.IsGenericParameter}"

// Get the generic type definition for Derived, and the base
// type for Derived.
let tDerived = typeof<Derived<_>>.GetGenericTypeDefinition()
let tDerivedBase = tDerived.BaseType

// Declare an array of Derived<int>, and get its type.
let d = Array.zeroCreate<Derived<int>> 0
let 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.
let tT = typeof<Base<_,_>>.GetGenericTypeDefinition().GetGenericArguments()[0]
let tF = tDerived.GetField("F").FieldType

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>>"

(* 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
 *)
Imports System.Reflection

' 
Public Class Base(Of T, U)
End Class

Public Class Derived(Of V) 
    Inherits Base(Of String, V)

    Public F As G(Of Derived(Of V))

    Public Class Nested
    End Class
End Class

Public Class G(Of T)
End Class 

Module Example

    Sub Main

        ' Get the generic type definition for Derived, and the base
        ' type for Derived.
        '
        Dim tDerived As Type = GetType(Derived(Of ))
        Dim tDerivedBase As Type = tDerived.BaseType

        ' Declare an array of Derived(Of Integer), and get its type.
        '
        Dim d(0) As Derived(Of Integer)
        Dim tDerivedArray As Type = 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(Of ), as shown here,
        ' or (2) specify a type parameter for Derived.
        '
        Dim tT As Type = GetType(Base(Of ,)).GetGenericArguments()(0)
        Dim tF As Type = tDerived.GetField("F").FieldType
        Dim tNested As Type = GetType(Derived(Of ).Nested)

        DisplayGenericType(tDerived, "Derived(Of V)")
        DisplayGenericType(tDerivedBase, "Base type of Derived(Of V)")
        DisplayGenericType(tDerivedArray, "Array of Derived(Of Integer)")
        DisplayGenericType(tT, "Type parameter T from Base(Of T)")
        DisplayGenericType(tF, "Field type, G(Of Derived(Of V))")
        DisplayGenericType(tNested, "Nested type in Derived(Of V)")

    End Sub

    Sub DisplayGenericType(ByVal t As Type, ByVal caption As String)

        Console.WriteLine(vbLf & caption)
        Console.WriteLine("    Type: {0}", t)

        Console.WriteLine(vbTab & "            IsGenericType: {0}", _
            t.IsGenericType)
        Console.WriteLine(vbTab & "  IsGenericTypeDefinition: {0}", _
            t.IsGenericTypeDefinition)
        Console.WriteLine(vbTab & "ContainsGenericParameters: {0}", _
            t.ContainsGenericParameters)
        Console.WriteLine(vbTab & "       IsGenericParameter: {0}", _
            t.IsGenericParameter)

    End Sub

End Module

' This code example produces the following output:
'
'Derived(Of V)
'    Type: Derived`1[V]
'                    IsGenericType: True
'          IsGenericTypeDefinition: True
'        ContainsGenericParameters: True
'               IsGenericParameter: False
'
'Base type of Derived(Of V)
'    Type: Base`2[System.String,V]
'                    IsGenericType: True
'          IsGenericTypeDefinition: False
'        ContainsGenericParameters: True
'               IsGenericParameter: False
'
'Array of Derived(Of Integer)
'    Type: Derived`1[System.Int32][]
'                    IsGenericType: False
'          IsGenericTypeDefinition: False
'        ContainsGenericParameters: False
'               IsGenericParameter: False
'
'Type parameter T from Base(Of T)
'    Type: T
'                    IsGenericType: False
'          IsGenericTypeDefinition: False
'        ContainsGenericParameters: True
'               IsGenericParameter: True
'
'Field type, G(Of Derived(Of V))
'    Type: G`1[Derived`1[V]]
'                    IsGenericType: True
'          IsGenericTypeDefinition: False
'        ContainsGenericParameters: True
'               IsGenericParameter: False
'
'Nested type in Derived(Of V)
'    Type: Derived`1+Nested[V]
'                    IsGenericType: True
'          IsGenericTypeDefinition: True
'        ContainsGenericParameters: True
'               IsGenericParameter: False

Remarques

Utilisez la IsGenericType propriété pour déterminer si un Type objet représente un type générique. Utilisez la ContainsGenericParameters propriété pour déterminer si un objet représente un Type type construit ouvert ou un type construit fermé.

Note

La IsGenericType propriété retourne false si le type immédiat n’est pas générique. Par exemple, un tableau dont les éléments sont de type A<int> (A(Of Integer) en Visual Basic) n’est pas lui-même un type générique.

Le tableau suivant récapitule les conditions invariantes des termes courants utilisés dans la réflexion générique.

Terme Invariant
définition de type générique La IsGenericTypeDefinition propriété est true.

Définit un type générique. Un type construit est créé en appelant la MakeGenericType méthode sur un Type objet qui représente une définition de type générique et en spécifiant un tableau d’arguments de type.

MakeGenericType peut être appelé uniquement sur les définitions de type générique.

Toute définition de type générique est un type générique (la IsGenericType propriété est true), mais l’inverse n’est pas vrai.
type générique La IsGenericType propriété est true.

Il peut s’agir d’une définition de type générique, d’un type construit ouvert ou d’un type construit fermé.

Notez qu’un type de tableau dont le type d’élément est générique n’est pas lui-même un type générique. Il en va de même d’un Type objet représentant un pointeur vers un type générique.
type construit ouvert La ContainsGenericParameters propriété est true.

Par exemple, un type générique qui a des paramètres de type non attribués, un type imbriqué dans une définition de type générique ou dans un type construit ouvert, ou un type générique qui a un argument de type pour lequel la ContainsGenericParameters propriété est true.

il n’est pas possible de créer une instance d’un type construit ouvert.

Notez que tous les types construits ouverts ne sont pas génériques. Par exemple, un tableau dont le type d’élément est une définition de type générique n’est pas générique et un pointeur vers un type construit ouvert n’est pas générique.
type construit fermé La ContainsGenericParameters propriété est false.

Lorsqu’il est examiné de manière récursive, le type n’a pas de paramètres génériques non attribués.
paramètre de type générique La IsGenericParameter propriété est true.

La ContainsGenericParameters propriété est true.

Dans une définition de type générique, un espace réservé pour un type qui sera affecté ultérieurement.
argument de type générique Peut être n’importe quel type, y compris un paramètre de type générique.

Les arguments de type sont spécifiés en tant que tableau d’objets passés à la méthode lors de Type la MakeGenericType création d’un type générique construit. Si des instances du type résultant doivent être créées, la ContainsGenericParameters propriété doit être false pour tous les arguments de type.

L’exemple de code et le tableau suivants illustrent certains de ces termes et invariants. La Derived classe est particulièrement intéressante, car son type de base est un type construit qui a un mélange de types et de paramètres de type dans sa liste d’arguments de type.

public class Base<T, U> {}

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

    public class Nested {}
}

public class G<T> {}
type Base<'T, 'U>() = class end

type G<'T>() = class end

type Derived<'V>() =
    inherit Base<string, 'V>()
    
    [<DefaultValue>]
    val mutable public F : G<Derived<'V>>
Public Class Base(Of T, U)
End Class

Public Class Derived(Of V)
    Inherits Base(Of String, V)

    Public F As G(Of Derived(Of V))

    Public Class Nested
    End Class
End Class

Public Class G(Of T)
End Class

Le tableau suivant présente des exemples qui utilisent et utilisent les classes Base, Derivedet G. Lorsque le code C++ et C# est le même, une seule entrée est affichée.

Exemple Invariants
Derived(Of V)

Derived<V>
Pour ce type :

IsGenericType a la valeur true.

IsGenericTypeDefinition a la valeur true.

ContainsGenericParameters a la valeur true.
Base(Of String, V)

Base<String,V>

Base<String^,V>
Pour ce type :

IsGenericType a la valeur true.

IsGenericTypeDefinition a la valeur false.

ContainsGenericParameters a la valeur true.
Dim d() As Derived(Of Integer)

Derived<int>[] d;

array<Derived<int>^>^ d;
Pour le type de variable d:

IsGenericType est false dû au fait qu’il d s’agit d’un tableau.

IsGenericTypeDefinition a la valeur false.

ContainsGenericParameters a la valeur false.
T, Uet V (partout où ils apparaissent) IsGenericParameter a la valeur true.

IsGenericType est false parce qu’il n’existe aucun moyen de limiter un paramètre de type aux types génériques.

IsGenericTypeDefinition a la valeur false.

ContainsGenericParameters est true parce que T, Uet V sont eux-mêmes des paramètres de type générique. Cela n’implique rien sur les arguments de type qui sont affectés ultérieurement.
Type de champ F IsGenericType a la valeur true.

IsGenericTypeDefinition est false parce qu’un type a été affecté au paramètre de type de G. Notez que cela équivaut à avoir appelé la MakeGenericType méthode.

ContainsGenericParameters est true parce que le type de champ F a un argument de type qui est un type construit ouvert. Le type construit est ouvert, car son argument de type (autrement dit, Base) est une définition de type générique. Cela illustre la nature récursive de la IsGenericType propriété.
Classe imbriquée Nested IsGenericType est true, même si la Nested classe n’a pas de paramètres de type générique propres, car elle est imbriquée dans un type générique.

IsGenericTypeDefinition a la valeur true. Autrement dit, vous pouvez appeler la MakeGenericType méthode et fournir le paramètre de type du type englobant, Derived.

ContainsGenericParameters est true dû au fait que le type englobant, a Deriveddes paramètres de type générique. Cela illustre la nature récursive de la ContainsGenericParameters propriété.

S’applique à

Voir aussi