Type.GenericParameterPosition Propriété

Définition

Obtient la position du paramètre de type dans la liste des paramètres de type du type générique ou de la méthode qui a déclaré le paramètre, quand l'objet Type représente un paramètre de type d'un type générique ou une méthode générique.

public:
 abstract property int GenericParameterPosition { int get(); };
public:
 virtual property int GenericParameterPosition { int get(); };
public abstract int GenericParameterPosition { get; }
public virtual int GenericParameterPosition { get; }
member this.GenericParameterPosition : int
Public MustOverride ReadOnly Property GenericParameterPosition As Integer
Public Overridable ReadOnly Property GenericParameterPosition As Integer

Valeur de propriété

Position d'un paramètre de type dans la liste des paramètres de type du type générique ou de la méthode qui a défini le paramètre. La numérotation des positions commence à zéro.

Exceptions

Le type actuel ne représente pas un paramètre de type. Autrement dit, IsGenericParameter retourne false.

Exemples

L’exemple suivant définit une classe générique avec deux paramètres de type et définit une deuxième classe générique qui dérive de la première classe. La classe de base de la classe dérivée a deux arguments de type : le premier est Int32et le second est un paramètre de type du type dérivé. L’exemple affiche des informations sur ces classes génériques, y compris les positions signalées par la GenericParameterPosition propriété .

using namespace System;
using namespace System::Reflection;
using namespace System::Collections::Generic;

// Define a base class with two type parameters.
generic< class T,class U >
public ref class Base {};

// Define a derived class. The derived class inherits from a constructed
// class that meets the following criteria:
//   (1) Its generic type definition is Base<T, U>.
//   (2) It specifies int for the first type parameter.
//   (3) For the second type parameter, it uses the same type that is used
//       for the type parameter of the derived class.
// Thus, the derived class is a generic type with one type parameter, but
// its base class is an open constructed type with one type argument and
// one type parameter.
generic<class V>
public ref class Derived : Base<int,V> {};

public ref class Test
{
public:
    static void Main()
    {
        Console::WriteLine( 
            L"\r\n--- Display a generic type and the open constructed");
        Console::WriteLine(L"    type from which it is derived.");
      
        // Create a Type object representing the generic type definition
        // for the Derived type. Note the absence of type arguments.
        //
        Type^ derivedType = Derived::typeid;
        DisplayGenericTypeInfo(derivedType);
      
        // Display its open constructed base type.
        DisplayGenericTypeInfo(derivedType->BaseType);
    }


private:
    static void DisplayGenericTypeInfo(Type^ t)
    {
        Console::WriteLine(L"\r\n{0}", t);
        Console::WriteLine(L"\tIs this a generic type definition? {0}",
            t->IsGenericTypeDefinition);
        Console::WriteLine(L"\tIs it a generic type? {0}", t->IsGenericType);
        Console::WriteLine(L"\tDoes it have unassigned generic parameters? {0}",
            t->ContainsGenericParameters);
        if (t->IsGenericType)
        {
         
            // If this is a generic type, display the type arguments.
            //
            array<Type^>^typeArguments = t->GetGenericArguments();
            Console::WriteLine(L"\tList type arguments ({0}):",
                typeArguments->Length);
            System::Collections::IEnumerator^ myEnum = 
                typeArguments->GetEnumerator();
            while (myEnum->MoveNext())
            {
                Type^ tParam = safe_cast<Type^>(myEnum->Current);
            
                // IsGenericParameter is true only for generic type
                // parameters.
                //
                if (tParam->IsGenericParameter)
                {
                    Console::WriteLine( 
                        L"\t\t{0}  (unassigned - parameter position {1})", 
                        tParam, tParam->GenericParameterPosition);
                }
                else
                {
                    Console::WriteLine(L"\t\t{0}", tParam);
                }
            }
        }
    }
};

int main()
{
    Test::Main();
}

/* This example produces the following output:

--- Display a generic type and the open constructed
    type from which it is derived.

Derived`1[V]
        Is this a generic type definition? True
        Is it a generic type? True
        Does it have unassigned generic parameters? True
        List type arguments (1):
                V  (unassigned - parameter position 0)

Base`2[System.Int32,V]
        Is this a generic type definition? False
        Is it a generic type? True
        Does it have unassigned generic parameters? True
        List type arguments (2):
                System.Int32
                V  (unassigned - parameter position 0)
 */
using System;
using System.Reflection;
using System.Collections.Generic;

// Define a base class with two type parameters.
public class Base<T, U> { }

// Define a derived class. The derived class inherits from a constructed
// class that meets the following criteria:
//   (1) Its generic type definition is Base<T, U>.
//   (2) It specifies int for the first type parameter.
//   (3) For the second type parameter, it uses the same type that is used
//       for the type parameter of the derived class.
// Thus, the derived class is a generic type with one type parameter, but
// its base class is an open constructed type with one type argument and
// one type parameter.
public class Derived<V> : Base<int, V> { }

public class Test
{
    public static void Main()
    {
        Console.WriteLine(
            "\r\n--- Display a generic type and the open constructed");
        Console.WriteLine("    type from which it is derived.");

        // Create a Type object representing the generic type definition 
        // for the Derived type, by omitting the type argument. (For
        // types with multiple type parameters, supply the commas but
        // omit the type arguments.) 
        //
        Type derivedType = typeof(Derived<>);
        DisplayGenericTypeInfo(derivedType);

        // Display its open constructed base type.
        DisplayGenericTypeInfo(derivedType.BaseType);
    }

    private static void DisplayGenericTypeInfo(Type t)
    {
        Console.WriteLine("\r\n{0}", t);

        Console.WriteLine("\tIs this a generic type definition? {0}", 
            t.IsGenericTypeDefinition);

        Console.WriteLine("\tIs it a generic type? {0}", 
            t.IsGenericType);

        Console.WriteLine("\tDoes it have unassigned generic parameters? {0}", 
            t.ContainsGenericParameters);

        if (t.IsGenericType)
        {
            // If this is a generic type, display the type arguments.
            //
            Type[] typeArguments = t.GetGenericArguments();

            Console.WriteLine("\tList type arguments ({0}):", 
                typeArguments.Length);

            foreach (Type tParam in typeArguments)
            {
                // IsGenericParameter is true only for generic type
                // parameters.
                //
                if (tParam.IsGenericParameter)
                {
                    Console.WriteLine(
                        "\t\t{0}  (unassigned - parameter position {1})",
                        tParam,
                        tParam.GenericParameterPosition);
                }
                else
                {
                    Console.WriteLine("\t\t{0}", tParam);
                }
            }
        }
    }
}

/* This example produces the following output:

--- Display a generic type and the open constructed
    type from which it is derived.

Derived`1[V]
        Is this a generic type definition? True
        Is it a generic type? True
        Does it have unassigned generic parameters? True
        List type arguments (1):
                V  (unassigned - parameter position 0)

Base`2[System.Int32,V]
        Is this a generic type definition? False
        Is it a generic type? True
        Does it have unassigned generic parameters? True
        List type arguments (2):
                System.Int32
                V  (unassigned - parameter position 0)
 */
open System
open System.Reflection
open System.Collections.Generic

// Define a base class with two type parameters.
type Base<'T, 'U>() = class end

// Define a derived class. The derived class inherits from a constructed
// class that meets the following criteria:
//   (1) Its generic type definition is Base<T, U>.
//   (2) It specifies int for the first type parameter.
//   (3) For the second type parameter, it uses the same type that is used
//       for the type parameter of the derived class.
// Thus, the derived class is a generic type with one type parameter, but
// its base class is an open constructed type with one type argument and
// one type parameter.
type Derived<'V>() = inherit Base<int, 'V>()

let displayGenericTypeInfo (t: Type) =
    printfn $"\n{t}"
    printfn $"\tIs this a generic type definition? {t.IsGenericTypeDefinition}"
    printfn $"\tIs it a generic type? {t.IsGenericType}"
    printfn $"\tDoes it have unassigned generic parameters? {t.ContainsGenericParameters}"

    if t.IsGenericType then
        // If this is a generic type, display the type arguments.
        let typeArguments = t.GetGenericArguments()

        printfn $"\tList type arguments ({typeArguments.Length}):"

        for tParam in typeArguments do
            // IsGenericParameter is true only for generic type
            // parameters.
            if tParam.IsGenericParameter then
                printfn $"\t\t{tParam}  (unassigned - parameter position {tParam.GenericParameterPosition})"
            else
                printfn $"\t\t{tParam}"

printfn $"\r\n--- Display a generic type and the open constructed"
printfn $"    type from which it is derived."

// Create a Type object representing the generic type definition 
// for the Derived type, by omitting the type argument. (For
// types with multiple type parameters, supply the commas but
// omit the type arguments.) 
//
let derivedType = (typeof<Derived<_>>).GetGenericTypeDefinition()
displayGenericTypeInfo derivedType

// Display its open constructed base type.
displayGenericTypeInfo derivedType.BaseType

(* This example produces the following output:

--- Display a generic type and the open constructed
    type from which it is derived.

Derived`1[V]
        Is this a generic type definition? True
        Is it a generic type? True
        Does it have unassigned generic parameters? True
        List type arguments (1):
                V  (unassigned - parameter position 0)

Base`2[System.Int32,V]
        Is this a generic type definition? False
        Is it a generic type? True
        Does it have unassigned generic parameters? True
        List type arguments (2):
                System.Int32
                V  (unassigned - parameter position 0)
 *)
Imports System.Reflection
Imports System.Collections.Generic

' Define a base class with two type parameters.
Public Class Base(Of T, U)
End Class

' Define a derived class. The derived class inherits from a constructed
' class that meets the following criteria:
'   (1) Its generic type definition is Base<T, U>.
'   (2) It uses int for the first type parameter.
'   (3) For the second type parameter, it uses the same type that is used
'       for the type parameter of the derived class.
' Thus, the derived class is a generic type with one type parameter, but
' its base class is an open constructed type with one assigned type
' parameter and one unassigned type parameter.
Public Class Derived(Of V)
    Inherits Base(Of Integer, V)
End Class

Public Class Test
    
    Public Shared Sub Main() 
        Console.WriteLine(vbCrLf _
            & "--- Display a generic type and the open constructed")
        Console.WriteLine("    type from which it is derived.")
        
        ' Create a Type object representing the generic type definition 
        ' for the Derived type, by omitting the type argument. (For
        ' types with multiple type parameters, supply the commas but
        ' omit the type arguments.) 
        '
        Dim derivedType As Type = GetType(Derived(Of ))
        DisplayGenericTypeInfo(derivedType)
        
        ' Display its open constructed base type.
        DisplayGenericTypeInfo(derivedType.BaseType)
    
    End Sub
    
    Private Shared Sub DisplayGenericTypeInfo(ByVal t As Type) 
        Console.WriteLine(vbCrLf & "{0}", t)
        
        Console.WriteLine(vbTab & "Is this a generic type definition? " _
            & t.IsGenericTypeDefinition)
        
        Console.WriteLine(vbTab & "Is it a generic type? " _
            & t.IsGenericType)
        
        Console.WriteLine(vbTab _
            & "Does it have unassigned generic parameters? " _
            & t.ContainsGenericParameters)
        
        If t.IsGenericType Then
            ' If this is a generic type, display the type arguments.
            '
            Dim typeArguments As Type() = t.GetGenericArguments()
            
            Console.WriteLine(vbTab & "List type arguments (" _
                & typeArguments.Length & "):")
            
            For Each tParam As Type In typeArguments
                ' IsGenericParameter is true only for generic type
                ' parameters.
                '
                If tParam.IsGenericParameter Then
                    Console.WriteLine(vbTab & vbTab & tParam.ToString() _
                        & "  (unassigned - parameter position " _
                        & tParam.GenericParameterPosition & ")")
                Else
                    Console.WriteLine(vbTab & vbTab & tParam.ToString())
                End If
            Next tParam
        End If
    
    End Sub
End Class

' This example produces the following output:
'
'--- Display a generic type and the open constructed
'    type from which it is derived.
'
'Derived`1[V]
'        Is this a generic type definition? True
'        Is it a generic type? True
'        Does it have unassigned generic parameters? True
'        List type arguments (1):
'                V  (unassigned - parameter position 0)
'
'Base`2[System.Int32,V]
'        Is this a generic type definition? False
'        Is it a generic type? True
'        Does it have unassigned generic parameters? True
'        List type parameters (2):
'                System.Int32
'                V  (unassigned - parameter position 0)
'

Remarques

La GenericParameterPosition propriété retourne la position d’un paramètre de type dans la liste de paramètres de la définition de type générique ou de la définition de méthode générique où le paramètre de type a été défini à l’origine. Les DeclaringType propriétés et DeclaringMethod identifient le type générique ou la définition de méthode :

  • Si la DeclaringMethod propriété retourne un MethodInfo, qui MethodInfo représente une définition de méthode générique, et l’objet actuel Type représente un paramètre de type de cette définition de méthode générique.

  • Si la DeclaringMethod propriété retourne null, la DeclaringType propriété renvoie toujours un Type objet représentant une définition de type générique, et l’objet actuel Type représente un paramètre de type de cette définition de type générique.

Pour fournir le contexte correct pour la valeur de la GenericParameterPosition propriété, il est nécessaire d’identifier le type ou la méthode générique auquel appartient un paramètre de type. Par exemple, considérez la valeur de retour de la méthode GetSomething générique dans le code suivant :

generic<typename T, typename U> public ref class B { };
generic<typename V> public ref class A
{
public:
    generic<typename X> B<V, X>^ GetSomething()
    {
        return gcnew B<V, X>();
    }
};
public class B<T, U> { }
public class A<V>
{
    public B<V, X> GetSomething<X>()
    {
        return new B<V, X>();
    }
}
type B<'T, 'U>() = class end
type A<'V>() =
    member _.GetSomething<'X>() =
        B<'V, 'X>()
Public Class B(Of T, U)
End Class
Public Class A(Of V)
    Public Function GetSomething(Of X)() As B(Of V, X)
        Return New B(Of V, X)()
    End Function
End Class

Le type retourné par GetSomething dépend des arguments de type fournis à la classe A et à GetSomething elle-même. Vous pouvez obtenir un MethodInfo pour GetSomething, et à partir de celui-ci, vous pouvez obtenir le type de retour. Lorsque vous examinez les paramètres de type du type de retour, GenericParameterPosition retourne 0 pour les deux. La position de V est 0, car V est le premier paramètre de type dans la liste des paramètres de type pour la classe A. La position de X est 0, car X est le premier paramètre de type dans la liste des paramètres de type pour GetSomething.

Notes

L’appel de la GenericParameterPosition propriété provoque une exception si le actuel Type ne représente pas un paramètre de type. Lorsque vous examinez les arguments de type d’un type construit ouvert, utilisez la IsGenericParameter propriété pour déterminer quels sont les paramètres de type et les types. La IsGenericParameter propriété retourne true pour un paramètre de type ; vous pouvez ensuite utiliser la GenericParameterPosition méthode pour obtenir sa position et utiliser les DeclaringMethod propriétés et DeclaringType pour déterminer la méthode générique ou la définition de type qui la définit.

S’applique à

Voir aussi