Type.GenericParameterPosition Type.GenericParameterPosition Type.GenericParameterPosition Type.GenericParameterPosition Property

定義

Type 物件表示泛型類型或泛型方法的類型參數時,在宣告參數的泛型類型或泛型方法之類型參數清單中,取得類型參數的位置。Gets the position of the type parameter in the type parameter list of the generic type or method that declared the parameter, when the Type object represents a type parameter of a generic type or a generic method.

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

屬性值

型別參數在宣告參數的泛型類型或方法之型別參數清單中的位置。The position of a type parameter in the type parameter list of the generic type or method that defines the parameter. 位置編號從 0 開始。Position numbers begin at 0.

例外狀況

目前類型不代表類型參數。The current type does not represent a type parameter. 亦即,IsGenericParameter 會傳回 falseThat is, IsGenericParameter returns false.

範例

下列範例會定義具有兩個類型參數的泛型類別,並定義第二個泛型類別衍生自第一個類別。The following example defines a generic class with two type parameters and defines a second generic class that derives from the first class. 在衍生的類別的基底類別具有兩個類型引數: 第一個是Int32,第二個是衍生型別的型別參數。The derived class's base class has two type arguments: the first is Int32, and the second is a type parameter of the derived type. 此範例會顯示這些泛型類別的相關資訊,包括位置報告GenericParameterPosition屬性。The example displays information about these generic classes, including the positions reported by the GenericParameterPosition property.

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)
 */
Imports System
Imports System.Reflection
Imports System.Collections.Generic
Imports Microsoft.VisualBasic

' 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 'Main
    
    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 'DisplayGenericTypeInfo
End Class 'Test

' 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)
' 

備註

GenericParameterPosition屬性會傳回型別參數的位置中的泛型型別定義或泛型方法定義的參數清單的型別參數原本定義。The GenericParameterPosition property returns the position of a type parameter in the parameter list of the generic type definition or generic method definition where the type parameter was originally defined. DeclaringTypeDeclaringMethod屬性識別的泛型型別或方法定義:The DeclaringType and DeclaringMethod properties identify the generic type or method definition:

  • 如果DeclaringMethod屬性會傳回MethodInfo,、 該MethodInfo代表泛型方法定義,以及目前Type物件都代表該泛型方法定義的型別參數。If the DeclaringMethod property returns a MethodInfo, that MethodInfo represents a generic method definition, and the current Type object represents a type parameter of that generic method definition.

  • 如果DeclaringMethod屬性會傳回null,則DeclaringType屬性一律會傳回Type物件,代表泛型類型定義和目前Type物件都代表該泛型類型的型別參數定義。If the DeclaringMethod property returns null, then the DeclaringType property always returns a Type object representing a generic type definition, and the current Type object represents a type parameter of that generic type definition.

若要提供正確的內容值的GenericParameterPosition屬性,就必須找出的泛型類型或方法所屬的型別參數。To provide the correct context for the value of the GenericParameterPosition property, it is necessary to identify the generic type or method a type parameter belongs to. 例如,請考慮泛型方法的傳回值GetSomething下列程式碼:For example, consider the return value of the generic method GetSomething in the following code:

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>();
    }
}
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

傳回的型別GetSomething取決於提供給類別的型別引數A以及GetSomething本身。The type returned by GetSomething depends on the type arguments supplied to class A and to GetSomething itself. 您可以取得MethodInfo針對GetSomething,以及您可以從所取得的傳回型別。You can obtain a MethodInfo for GetSomething, and from that you can obtain the return type. 當您檢查型別參數的傳回型別,GenericParameterPosition兩者會傳回 0。When you examine the type parameters of the return type, GenericParameterPosition returns 0 for both. 位置V為 0,因為V類別的型別參數清單中的第一個型別參數AThe position of V is 0 because V is the first type parameter in the type parameter list for class A. 位置X為 0,因為X的型別參數清單中的第一個型別參數GetSomethingThe position of X is 0 because X is the first type parameter in the type parameter list for GetSomething.

注意

呼叫GenericParameterPosition屬性會造成例外狀況,如果目前Type不代表型別參數。Calling the GenericParameterPosition property causes an exception if the current Type does not represent a type parameter. 當您檢查開放式建構類型的類型引數時,使用IsGenericParameter告訴它們在型別參數,以及這是類型的屬性。When you examine the type arguments of an open constructed type, use the IsGenericParameter property to tell which are type parameters and which are types. IsGenericParameter屬性會傳回true型別參數; 您可以接著使用GenericParameterPosition方法來取得它的位置,並使用DeclaringMethodDeclaringType來判斷泛型方法或類型定義中定義的屬性.The IsGenericParameter property returns true for a type parameter; you can then use the GenericParameterPosition method to obtain its position and use the DeclaringMethod and DeclaringType properties to determine the generic method or type definition that defines it.

適用於

另請參閱