Type.MakeGenericType(Type[]) 方法

定义

替代由当前泛型类型定义的类型参数组成的类型数组的元素,并返回表示结果构造类型的 Type 对象。Substitutes the elements of an array of types for the type parameters of the current generic type definition and returns a Type object representing the resulting constructed type.

public:
 virtual Type ^ MakeGenericType(... cli::array <Type ^> ^ typeArguments);
public virtual Type MakeGenericType (params Type[] typeArguments);
abstract member MakeGenericType : Type[] -> Type
override this.MakeGenericType : Type[] -> Type
Public Overridable Function MakeGenericType (ParamArray typeArguments As Type()) As Type

参数

typeArguments
Type[]

将代替当前泛型类型的类型参数的类型数组。An array of types to be substituted for the type parameters of the current generic type.

返回

Type 表示的构造类型通过以下方式形成:用 typeArguments 的元素取代当前泛型类型的类型参数。A Type representing the constructed type formed by substituting the elements of typeArguments for the type parameters of the current generic type.

异常

当前的类型不表示泛型类型定义。The current type does not represent a generic type definition. 也就是说,IsGenericTypeDefinition 返回 falseThat is, IsGenericTypeDefinition returns false.

typeArgumentsnulltypeArguments is null.

- 或 --or- typeArguments 的任意元素为 nullAny element of typeArguments is null.

typeArguments 中的元素数与当前泛型类型定义中的类型参数数不同。The number of elements in typeArguments is not the same as the number of type parameters in the current generic type definition.

-or- typeArguments 的所有元素都不满足为当前泛型类型的相应类型参数指定的约束。Any element of typeArguments does not satisfy the constraints specified for the corresponding type parameter of the current generic type.

- 或 --or- typeArguments 包含一个元素,该元素是一个指针类型(IsPointer 返回 true)、by-ref 类型(IsByRef 返回 true)或 VoidtypeArguments contains an element that is a pointer type (IsPointer returns true), a by-ref type (IsByRef returns true), or Void.

基类不支持调用的方法。The invoked method is not supported in the base class. 派生类必须提供一个实现。Derived classes must provide an implementation.

示例

下面的示例使用MakeGenericType方法从Dictionary<TKey,TValue>类型的泛型类型定义中创建构造类型。The following example uses the MakeGenericType method to create a constructed type from the generic type definition for the Dictionary<TKey,TValue> type. 构造类型表示Dictionary<TKey,TValue>具有字符串键Test的对象的。The constructed type represents a Dictionary<TKey,TValue> of Test objects with string keys.

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

namespace Example
{
    public ref class Test
    {
    public:
        static void CreateConstructedType(void)
        {      
            Console::WriteLine("\r\n--- Create a constructed type"
                " from the generic Dictionary`2 type.");
            
            // Create a type object representing 
            // the generic Dictionary`2 type.
            Type^ genericType = Type::GetType(
                "System.Collections.Generic.Dictionary`2");
            if (genericType != nullptr)
            {  
                DisplayTypeInfo(genericType);
            }
            else
            {
                Console::WriteLine("The type is not found");
                return;
            }
            
            // Create an array of types to substitute for the type
            // parameters of Dictionary`2. 
            // The key is of type string, and the type to be 
            // contained in the Dictionary`2 is Test.
            array<Type^>^ typeArgs = {String::typeid, Test::typeid};
            Type^ constructedType = 
                genericType->MakeGenericType(typeArgs);
            DisplayTypeInfo(constructedType);
            
            // Compare the type objects obtained above to type objects
            // obtained using typeof() and GetGenericTypeDefinition().
            Console::WriteLine("\r\n--- Compare types obtained by"
                " different methods:");

            Type^ definedType = Dictionary<String^, Test^>::typeid;
            Console::WriteLine("\tAre the constructed types "
                "equal? {0}", definedType == constructedType);
            Console::WriteLine("\tAre the generic types equal? {0}", 
                definedType->GetGenericTypeDefinition() == genericType);
        }

    private:
        static void DisplayTypeInfo(Type^ typeToDisplay)
        {   
            Console::WriteLine("\r\n{0}", typeToDisplay);
            Console::WriteLine("\tIs this a generic type definition? "
                "{0}", typeToDisplay->IsGenericTypeDefinition);
            Console::WriteLine("\tIs it a generic type? "
                "{0}", typeToDisplay->IsGenericType);
            
            array<Type^>^ typeArguments = 
                typeToDisplay->GetGenericArguments();
            Console::WriteLine("\tList type arguments ({0}):", 
                typeArguments->Length);
            
            for each (Type^ typeArgument in typeArguments)
            {   
                Console::WriteLine("\t\t{0}", typeArgument);
            }
        }
    };
}

int main(void)
{
    Example::Test::CreateConstructedType();
}

/* This example produces the following output:

--- Create a constructed type from the generic Dictionary`2 type.

System.Collections.Generic.Dictionary`2[KeyType,ValueType]
          Is this a generic type definition? True
          Is it a generic type? True
          List type arguments (2):
                     K
                     V

System.Collections.Generic.Dictionary`2[System.String, Test]
          Is this a generic type definition? False
          Is it a generic type? True
          List type arguments (2):
                     System.String
                     Test

--- Compare types obtained by different methods:
          Are the constructed types equal? True
          Are the generic types equal? True
 */
using System;
using System.Reflection;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        Console.WriteLine("\r\n--- Create a constructed type from the generic Dictionary type.");

        // Create a type object representing the generic Dictionary 
        // type, by omitting the type arguments (but keeping the 
        // comma that separates them, so the compiler can infer the
        // number of type parameters).      
        Type generic = typeof(Dictionary<,>);
        DisplayTypeInfo(generic);

        // Create an array of types to substitute for the type
        // parameters of Dictionary. The key is of type string, and
        // the type to be contained in the Dictionary is Test.
        Type[] typeArgs = { typeof(string), typeof(Test) };

        // Create a Type object representing the constructed generic
        // type.
        Type constructed = generic.MakeGenericType(typeArgs);
        DisplayTypeInfo(constructed);

        // Compare the type objects obtained above to type objects
        // obtained using typeof() and GetGenericTypeDefinition().
        Console.WriteLine("\r\n--- Compare types obtained by different methods:");

        Type t = typeof(Dictionary<String, Test>);
        Console.WriteLine("\tAre the constructed types equal? {0}", t == constructed);
        Console.WriteLine("\tAre the generic types equal? {0}", 
            t.GetGenericTypeDefinition() == generic);
    }

    private static void DisplayTypeInfo(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);

        Type[] typeArguments = t.GetGenericArguments();
        Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length);
        foreach (Type tParam in typeArguments)
        {
            Console.WriteLine("\t\t{0}", tParam);
        }
    }
}

/* This example produces the following output:

--- Create a constructed type from the generic Dictionary type.

System.Collections.Generic.Dictionary`2[TKey,TValue]
        Is this a generic type definition? True
        Is it a generic type? True
        List type arguments (2):
                TKey
                TValue

System.Collections.Generic.Dictionary`2[System.String, Test]
        Is this a generic type definition? False
        Is it a generic type? True
        List type arguments (2):
                System.String
                Test

--- Compare types obtained by different methods:
        Are the constructed types equal? True
        Are the generic types equal? True
 */
Imports System.Reflection
Imports System.Collections.Generic

Public Class Test
    Public Shared Sub Main()
        Console.WriteLine(vbCrLf & "--- Create a constructed type from the generic Dictionary type.")

        ' Create a type object representing the generic Dictionary 
        ' type, by omitting the type arguments (but keeping the 
        ' comma that separates them, so the compiler can infer the
        ' number of type parameters).
        Dim generic As Type = GetType(Dictionary(Of ,))
        DisplayTypeInfo(generic)

        ' Create an array of types to substitute for the type
        ' parameters of Dictionary. The key is of type string, and
        ' the type to be contained in the Dictionary is Test.
        Dim typeArgs() As Type = { GetType(String), GetType(Test) }

        ' Create a Type object representing the constructed generic
        ' type.
        Dim constructed As Type = generic.MakeGenericType(typeArgs)
        DisplayTypeInfo(constructed)

        ' Compare the type objects obtained above to type objects
        ' obtained using GetType() and GetGenericTypeDefinition().
        Console.WriteLine(vbCrLf & "--- Compare types obtained by different methods:")

        Dim t As Type = GetType(Dictionary(Of String, Test))
        Console.WriteLine(vbTab & "Are the constructed types equal? " _
            & (t Is constructed))
        Console.WriteLine(vbTab & "Are the generic types equal? " _ 
            & (t.GetGenericTypeDefinition() Is generic))
    End Sub

    Private Shared Sub DisplayTypeInfo(ByVal t As Type)
        Console.WriteLine(vbCrLf & t.ToString())

        Console.WriteLine(vbTab & "Is this a generic type definition? " _ 
            & t.IsGenericTypeDefinition)

        Console.WriteLine(vbTab & "Is it a generic type? " _ 
            & t.IsGenericType)

        Dim typeArguments() As Type = t.GetGenericArguments()
        Console.WriteLine(vbTab & "List type arguments ({0}):", _
            typeArguments.Length)
        For Each tParam As Type In typeArguments       
            Console.WriteLine(vbTab & vbTab & tParam.ToString())
        Next
    End Sub
End Class

' This example produces the following output:
'
'--- Create a constructed type from the generic Dictionary type.
'
'System.Collections.Generic.Dictionary'2[TKey,TValue]
'        Is this a generic type definition? True
'        Is it a generic type? True
'        List type arguments (2):
'                TKey
'                TValue
'
'System.Collections.Generic.Dictionary`2[System.String,Test]
'        Is this a generic type definition? False
'        Is it a generic type? True
'        List type arguments (2):
'                System.String
'                Test
'
'--- Compare types obtained by different methods:
'        Are the constructed types equal? True
'        Are the generic types equal? True

注解

使用MakeGenericType方法,可以编写将特定类型分配给泛型类型定义的类型参数的代码,从而Type创建表示特定构造类型的对象。The MakeGenericType method allows you to write code that assigns specific types to the type parameters of a generic type definition, thus creating a Type object that represents a particular constructed type. 您可以使用此Type对象创建构造类型的运行时实例。You can use this Type object to create run-time instances of the constructed type.

MakeGenericType构造的类型可以是开放的,也就是说,它们的某些类型参数可以是封闭泛型方法或类型的类型参数。Types constructed with MakeGenericType can be open, that is, some of their type arguments can be type parameters of enclosing generic methods or types. 发出动态程序集时,可以使用此类开放式构造类型。You might use such open constructed types when you emit dynamic assemblies. 例如,请考虑以下代码BaseDerived的类和。For example, consider the classes Base and Derived in the following code.

generic<typename T, typename U>
    public ref class Base { };
generic<typename V>
    public ref class Derived : Base<int, V> { };
public class Base<T, U> { }
public class Derived<V> : Base<int, V> { }
Public Class Base(Of T, U)
End Class
Public Class Derived(Of V)
    Inherits Base(Of Integer, V)
End Class

若要Derived在动态程序集中生成,需要构造其基类型。To generate Derived in a dynamic assembly, it is necessary to construct its base type. 为此,请使用泛型MakeGenericType类型参数Int32TypeV Derived的类型参数Base对表示类的对象调用方法。To do this, call the MakeGenericType method on a Type object representing the class Base, using the generic type arguments Int32 and the type parameter V from Derived. 因为类型和泛型类型参数均由Type对象表示,所以,同时包含这两个参数的数组可传递MakeGenericType给方法。Because types and generic type parameters are both represented by Type objects, an array containing both can be passed to the MakeGenericType method.

备注

发出代码时,构造Base<int, V>类型(如)非常有用,但不能对MakeGenericType此类型调用方法,因为它不是泛型类型定义。A constructed type such as Base<int, V> is useful when emitting code, but you cannot call the MakeGenericType method on this type because it is not a generic type definition. 若要创建可以实例化的封闭式构造类型,请首先调用GetGenericTypeDefinition方法Type获取表示泛型类型定义的对象,然后使用所需MakeGenericType的类型参数调用。To create a closed constructed type that can be instantiated, first call the GetGenericTypeDefinition method to get a Type object representing the generic type definition and then call MakeGenericType with the desired type arguments.

GetType GetType Type返回的对象与通过调用生成的构造类型的方法获得的相同,或从相同泛型创建的任何构造类型的方法相同。 Type MakeGenericType类型定义使用相同的类型参数。The Type object returned by MakeGenericType is the same as the Type obtained by calling the GetType method of the resulting constructed type, or the GetType method of any constructed type that was created from the same generic type definition using the same type arguments.

备注

泛型类型的数组本身不是泛型类型。An array of generic types is not itself a generic type. 不能对MakeGenericType数组类型C<T>[]Dim ac() As C(Of T)如 Visual Basic)调用。You cannot call MakeGenericType on an array type such as C<T>[] (Dim ac() As C(Of T) in Visual Basic). C<T>[]要从构造封闭式泛型类型,请GetElementType调用以获取泛型类型定义C<T>; 对MakeGenericType泛型类型MakeArrayType定义调用以创建构造类型; 最后调用方法用于创建数组类型的构造类型。To construct a closed generic type from C<T>[], call GetElementType to obtain the generic type definition C<T>; call MakeGenericType on the generic type definition to create the constructed type; and finally call the MakeArrayType method on the constructed type to create the array type. 指针类型和ref类型(ByRef在 Visual Basic)中也是如此。The same is true of pointer types and ref types (ByRef in Visual Basic).

有关泛型反射中使用的术语的固定条件列表,请参阅 IsGenericType 属性注解。For a list of the invariant conditions for terms used in generic reflection, see the IsGenericType property remarks.

嵌套类型Nested Types

如果使用C#、 C++或 Visual Basic 定义泛型类型,则其嵌套类型都是泛型类型。If a generic type is defined using C#, C++, or Visual Basic, then its nested types are all generic. 即使嵌套类型没有自己的类型参数,也是如此,因为所有这三种语言都包括嵌套类型的类型参数列表中的封闭类型的类型参数。This is true even if the nested types have no type parameters of their own, because all three languages include the type parameters of enclosing types in the type parameter lists of nested types. 请考虑以下类:Consider the following classes:

generic<typename T> public ref class Outermost
{
public:
    generic<typename U> ref class Inner
    {
    public:
        generic<typename V> ref class Innermost1 {};
        ref class Innermost2 {};
    };
};
public class Outermost<T>
{
    public class Inner<U>
    {
        public class Innermost1<V> {}
        public class Innermost2 {}
    }
}
Public Class Outermost(Of T)
    Public Class Inner(Of U)
        Public Class Innermost1(Of V)
        End Class
        Public Class Innermost2
        End Class
    End Class
End Class

嵌套类Inner的类型参数列表具有两个类型参数UT第一个参数是其封闭类的类型参数。The type parameter list of the nested class Inner has two type parameters, T and U, the first of which is the type parameter of its enclosing class. 同样,嵌套类Innermost1的类型参数列表具有三个类型参数UT、和VT U它们来自其封闭类。Similarly, the type parameter list of the nested class Innermost1 has three type parameters, T, U, and V, with T and U coming from its enclosing classes. 嵌套类Innermost2有两个类型参数: TU,它们来自其封闭类。The nested class Innermost2 has two type parameters, T and U, which come from its enclosing classes.

如果封闭类型的参数列表具有多个类型参数,则按顺序列出的所有类型参数都包含在嵌套类型的类型参数列表中。If the parameter list of the enclosing type has more than one type parameter, all the type parameters in order are included in the type parameter list of the nested type.

若要从嵌套类型的泛型类型定义构造泛型类型,请通过连接MakeGenericType所有封闭类型的类型参数数组(从最外面的泛型类型开始,以嵌套类型本身的类型参数数组(如果它具有其自己的类型参数)。To construct a generic type from the generic type definition for a nested type, call the MakeGenericType method with the array formed by concatenating the type argument arrays of all the enclosing types, beginning with the outermost generic type, and ending with the type argument array of the nested type itself, if it has type parameters of its own. 若要创建的Innermost1实例,请使用包含三种类型的数组MakeGenericType调用方法,将其分配给 T、U 和 V。若要创建的Innermost2实例,请使用包含两个类型的数组MakeGenericType调用方法,将其分配给 T 和 U。To create an instance of Innermost1, call the MakeGenericType method with an array containing three types, to be assigned to T, U, and V. To create an instance of Innermost2, call the MakeGenericType method with an array containing two types, to be assigned to T and U.

语言以这种方式传播封闭类型的类型参数,因此可以使用封闭类型的类型参数来定义嵌套类型的字段。The languages propagate the type parameters of enclosing types in this fashion so you can use the type parameters of an enclosing type to define fields of nested types. 否则,类型参数将不会位于嵌套类型体内的范围内。Otherwise, the type parameters would not be in scope within the bodies of the nested types. 通过在动态程序集中发出代码或使用Ilasm (IL 汇编程序),可以定义嵌套类型而无需传播封闭类型的类型参数。It is possible to define nested types without propagating the type parameters of enclosing types, by emitting code in dynamic assemblies or by using the Ilasm.exe (IL Assembler). 对于 MSIL 组装器,请考虑以下代码:Consider the following code for the MSIL assembler:

.class public Outer<T> {  
    .class nested public Inner<U> {  
        .class nested public Innermost {  
        }  
    }  
}  

在此示例中,不能在类T Innermost中定义类型为或U的字段,因为这些类型参数不在范围内。In this example, it is not possible to define a field of type T or U in class Innermost, because those type parameters are not in scope. 以下汇编程序代码定义了嵌套类,它们的行为方式与它们在、 C++Visual Basic 和C#中定义的方式相同:The following assembler code defines nested classes that behave the way they would if defined in C++, Visual Basic, and C#:

.class public Outer<T> {  
    .class nested public Inner<T, U> {  
        .class nested public Innermost<T, U, V> {  
        }  
    }  
}  

可以使用Ildasm (IL 拆装器)检查在高级语言中定义的嵌套类,并观察此命名方案。You can use the Ildasm.exe (IL Disassembler) to examine nested classes defined in the high-level languages and observe this naming scheme.

适用于

另请参阅