TypeBuilder.GetConstructor(Type, ConstructorInfo) 方法

定義

傳回指定建構泛型類型的建構函式,其對應於泛型類型定義的指定建構函式。Returns the constructor of the specified constructed generic type that corresponds to the specified constructor of the generic type definition.

public:
 static System::Reflection::ConstructorInfo ^ GetConstructor(Type ^ type, System::Reflection::ConstructorInfo ^ constructor);
public static System.Reflection.ConstructorInfo GetConstructor (Type type, System.Reflection.ConstructorInfo constructor);
static member GetConstructor : Type * System.Reflection.ConstructorInfo -> System.Reflection.ConstructorInfo
Public Shared Function GetConstructor (type As Type, constructor As ConstructorInfo) As ConstructorInfo

參數

type
Type

傳回的是建構泛型類型的建構函式。The constructed generic type whose constructor is returned.

constructor
ConstructorInfo

指定要傳回哪個 type 建構函式 type 之泛型類型定義的建構函式。A constructor on the generic type definition of type, which specifies which constructor of type to return.

傳回

ConstructorInfo

表示對應 constructor (其指定屬於 type 泛型類型定義的建構函式) 的 type 建構函式的 ConstructorInfo 物件,。A ConstructorInfo object that represents the constructor of type corresponding to constructor, which specifies a constructor belonging to the generic type definition of type.

例外狀況

type 不代表泛型類型。type does not represent a generic type.

-或--or- type 不是 TypeBuilder型別。type is not of type TypeBuilder.

-或--or- constructor 的宣告類型不是泛型類型定義。The declaring type of constructor is not a generic type definition.

-或--or- constructor 的宣告類型不是 type 的泛型類型定義。The declaring type of constructor is not the generic type definition of type.

範例

下列程式碼範例包含名為之泛型類別的原始程式碼 Sample ,該類別具有名為的型別參數 TThe following code example contains source code for a generic class named Sample that has a type parameter named T. 類別具有名為、類型為的欄位,以及名為的 Field T 泛型方法,其名為的型別 GM 參數 UThe class has a field named Field, of type T, and a generic method named GM with its own type parameter, named U. 方法會 GM 建立的實例 Sample ,並以自己的型別參數取代的型別參數, U Sample 並將其輸入參數儲存在中 FieldMethod GM creates an instance of Sample, substituting its own type parameter U for the type parameter of Sample, and stores its input parameter in Field. 此原始程式碼已編譯但未使用;您可以使用 Ildasm.exe (IL 解譯器) 來加以查看,並將其與類別發出的程式碼進行比較 ExampleThis source code is compiled but not used; you can view it with the Ildasm.exe (IL Disassembler) and compare it to the code emitted by class Example.

類別中的程式碼會 Example 示範如何使用 GetConstructor 方法來發出泛型程式碼。The code in class Example demonstrates the use of the GetConstructor method to emit generic code. Main類別的方法會 Example 建立動態元件,其中包含名為的類別 Sample ,並使用方法,藉 DefineGenericParameters 由新增名為的類型參數來使其成為泛型 TThe Main method of class Example creates a dynamic assembly containing a class named Sample and uses the DefineGenericParameters method to make it generic by adding a type parameter named T. 無參數的函式和名為 Field 的欄位(屬於型別 T )都會加入至類別 SampleA parameterless constructor and a field named Field, of type T, are added to class Sample. 方法 GM 會使用方法來加入和轉換成泛型方法 MethodBuilder.DefineGenericParametersA method GM is added and turned into a generic method by using the MethodBuilder.DefineGenericParameters method. 的型別參數 GM 名為 UThe type parameter of GM is named U. 在定義型別參數之後, GM 就會使用方法來加入的簽章 MethodBuilder.SetSignatureAfter the type parameter is defined, the signature of GM is added by using the MethodBuilder.SetSignature method. 沒有傳回型別,而且沒有任何必要或自訂修飾詞,因此這個方法的所有參數都是例外,將 null parameterTypes parameterTypes 方法的唯一參數型別設定為 U ,方法的泛型型別參數。There is no return type and no required or custom modifiers, so all the parameters of this method are null except parameterTypes; parameterTypes sets the type of the method's only parameter to U, the method's generic type parameter. 方法的主體會在 Visual Basic) 中建立 (的結構化型別實例 Sample<U> Sample(Of U) ,將方法的參數指派給 Field ,然後列印的值 FieldThe body of the method creates an instance of the constructed type Sample<U> (Sample(Of U) in Visual Basic), assigns the method's parameter to Field, and then prints the value of Field. GetConstructor方法是用來建立,其 ConstructorInfo 代表在 Sample<U> 建立實例的指令中,所建立之泛型型別的無參數的函式 OpCodes.NewobjThe GetConstructor method is used to create a ConstructorInfo that represents the parameterless constructor of the constructed generic type Sample<U> in the OpCodes.Newobj instruction that creates the instance.

定義虛擬類型來保存進入點方法 MainA dummy type is defined to hold the entry-point method Main. 在的主體中 Main ,靜態 GM 方法會在 Visual Basic) 中的結構化泛型型別 (上叫 Sample<int> Sample(Of Integer) 用,其類型會 String 取代 UIn the body of Main, the static GM method is invoked on the constructed generic type Sample<int> (Sample(Of Integer) in Visual Basic), with type String substituted for U.

當程式碼範例執行時,它會將發出的元件儲存為 TypeBuilderGetFieldExample.exe。When the code example is run, it saves the emitted assembly as TypeBuilderGetFieldExample.exe. 您可以執行 TypeBuilderGetFieldExample.exe,也可以使用 Ildasm.exe (IL 解譯器) ,將發出的程式碼與 Sample 編譯成程式碼範例本身之類別的程式碼進行比較。You can run TypeBuilderGetFieldExample.exe, and you can use the Ildasm.exe (IL Disassembler) to compare the emitted code with the code for the Sample class that is compiled into the code example itself.

using System;
using System.Reflection;
using System.Reflection.Emit;

// Compare the MSIL in this class to the MSIL
// generated by the Reflection.Emit code in class
// Example.
public class Sample<T>
{
  public T Field;
  public static void GM<U>(U val)
  {
    Sample<U> s = new Sample<U>();
    s.Field = val;
    Console.WriteLine(s.Field);
  }
}

public class Example
{
    public static void Main()
    {
        AppDomain myDomain = AppDomain.CurrentDomain;
        AssemblyName myAsmName =
            new AssemblyName("TypeBuilderGetFieldExample");
        AssemblyBuilder myAssembly = myDomain.DefineDynamicAssembly(
            myAsmName, AssemblyBuilderAccess.Save);
        ModuleBuilder myModule = myAssembly.DefineDynamicModule(
            myAsmName.Name,
            myAsmName.Name + ".exe");

        // Define the sample type.
        TypeBuilder myType = myModule.DefineType("Sample",
            TypeAttributes.Class | TypeAttributes.Public);

        // Add a type parameter, making the type generic.
        string[] typeParamNames = {"T"};
        GenericTypeParameterBuilder[] typeParams =
            myType.DefineGenericParameters(typeParamNames);

        // Define a default constructor. Normally it would
        // not be necessary to define the default constructor,
        // but in this case it is needed for the call to
        // TypeBuilder.GetConstructor, which gets the default
        // constructor for the generic type constructed from
        // Sample<T>, in the generic method GM<U>.
        ConstructorBuilder ctor = myType.DefineDefaultConstructor(
            MethodAttributes.PrivateScope | MethodAttributes.Public |
            MethodAttributes.HideBySig | MethodAttributes.SpecialName |
            MethodAttributes.RTSpecialName);

        // Add a field of type T, with the name Field.
        FieldBuilder myField = myType.DefineField("Field",
            typeParams[0],
            FieldAttributes.Public);

        // Add a method and make it generic, with a type
        // parameter named U. Note how similar this is to
        // the way Sample is turned into a generic type. The
        // method has no signature, because the type of its
        // only parameter is U, which is not yet defined.
        MethodBuilder genMethod = myType.DefineMethod("GM",
            MethodAttributes.Public | MethodAttributes.Static);
        string[] methodParamNames = {"U"};
        GenericTypeParameterBuilder[] methodParams =
            genMethod.DefineGenericParameters(methodParamNames);

        // Now add a signature for genMethod, specifying U
        // as the type of the parameter. There is no return value
        // and no custom modifiers.
        genMethod.SetSignature(null, null, null,
            new Type[] { methodParams[0] }, null, null);

        // Emit a method body for the generic method.
        ILGenerator ilg = genMethod.GetILGenerator();
        // Construct the type Sample<U> using MakeGenericType.
        Type SampleOfU = myType.MakeGenericType( methodParams[0] );
        // Create a local variable to store the instance of
        // Sample<U>.
        ilg.DeclareLocal(SampleOfU);
        // Call the default constructor. Note that it is
        // necessary to have the default constructor for the
        // constructed generic type Sample<U>; use the
        // TypeBuilder.GetConstructor method to obtain this
        // constructor.
        ConstructorInfo ctorOfU = TypeBuilder.GetConstructor(
            SampleOfU, ctor);
        ilg.Emit(OpCodes.Newobj, ctorOfU);
        // Store the instance in the local variable; load it
        // again, and load the parameter of genMethod.
        ilg.Emit(OpCodes.Stloc_0);
        ilg.Emit(OpCodes.Ldloc_0);
        ilg.Emit(OpCodes.Ldarg_0);
        // In order to store the value in the field of the
        // instance of Sample<U>, it is necessary to have
        // a FieldInfo representing the field of the
        // constructed type. Use TypeBuilder.GetField to
        // obtain this FieldInfo.
        FieldInfo FieldOfU = TypeBuilder.GetField(
            SampleOfU, myField);
        // Store the value in the field.
        ilg.Emit(OpCodes.Stfld, FieldOfU);
        // Load the instance, load the field value, box it
        // (specifying the type of the type parameter, U), and
        // print it.
        ilg.Emit(OpCodes.Ldloc_0);
        ilg.Emit(OpCodes.Ldfld, FieldOfU);
        ilg.Emit(OpCodes.Box, methodParams[0]);
        MethodInfo writeLineObj =
            typeof(Console).GetMethod("WriteLine",
                new Type[] { typeof(object) });
        ilg.EmitCall(OpCodes.Call, writeLineObj, null);
        ilg.Emit(OpCodes.Ret);

        // Emit an entry point method; this must be in a
        // non-generic type.
        TypeBuilder dummy = myModule.DefineType("Dummy",
            TypeAttributes.Class | TypeAttributes.NotPublic);
        MethodBuilder entryPoint = dummy.DefineMethod("Main",
            MethodAttributes.Public | MethodAttributes.Static,
            null, null);
        ilg = entryPoint.GetILGenerator();
        // In order to call the static generic method GM, it is
        // necessary to create a constructed type from the
        // generic type definition for Sample. This can be any
        // constructed type; in this case Sample<int> is used.
        Type SampleOfInt =
            myType.MakeGenericType( typeof(int) );
        // Next get a MethodInfo representing the static generic
        // method GM on type Sample<int>.
        MethodInfo SampleOfIntGM = TypeBuilder.GetMethod(SampleOfInt,
            genMethod);
        // Next get a MethodInfo for GM<string>, which is the
        // instantiation of GM that Main calls.
        MethodInfo GMOfString =
            SampleOfIntGM.MakeGenericMethod( typeof(string) );
        // Finally, emit the call. Push a string onto
        // the stack, as the argument for the generic method.
        ilg.Emit(OpCodes.Ldstr, "Hello, world!");
        ilg.EmitCall(OpCodes.Call, GMOfString, null);
        ilg.Emit(OpCodes.Ret);

        myType.CreateType();
        dummy.CreateType();
        myAssembly.SetEntryPoint(entryPoint);
        myAssembly.Save(myAsmName.Name + ".exe");

        Console.WriteLine(myAsmName.Name + ".exe has been saved.");
    }
}
Imports System.Reflection
Imports System.Reflection.Emit

' Compare the MSIL in this class to the MSIL
' generated by the Reflection.Emit code in class
' Example.
Public Class Sample(Of T)
    Public Field As T
    Public Shared Sub GM(Of U)(ByVal val As U)
        Dim s As New Sample(Of U)
        s.Field = val
        Console.WriteLine(s.Field)
    
    End Sub
End Class 

Public Class Example
    
    Public Shared Sub Main() 
        Dim myDomain As AppDomain = AppDomain.CurrentDomain
        Dim myAsmName As New AssemblyName("TypeBuilderGetFieldExample")
        Dim myAssembly As AssemblyBuilder = _
            myDomain.DefineDynamicAssembly(myAsmName, _
                AssemblyBuilderAccess.Save)
        Dim myModule As ModuleBuilder = _
            myAssembly.DefineDynamicModule(myAsmName.Name, _
                myAsmName.Name & ".exe")
        
        ' Define the sample type.
        Dim myType As TypeBuilder = myModule.DefineType( _
            "Sample", _
            TypeAttributes.Class Or TypeAttributes.Public)
        
        ' Add a type parameter, making the type generic.
        Dim typeParamNames() As String = { "T" }
        Dim typeParams As GenericTypeParameterBuilder() = _
            myType.DefineGenericParameters(typeParamNames)
        
        ' Define a default constructor. Normally it would 
        ' not be necessary to define the default constructor,
        ' but in this case it is needed for the call to
        ' TypeBuilder.GetConstructor, which gets the default
        ' constructor for the generic type constructed from 
        ' Sample(Of T), in the generic method GM(Of U).
        Dim ctor As ConstructorBuilder = _
            myType.DefineDefaultConstructor( _
                MethodAttributes.PrivateScope Or MethodAttributes.Public _
                Or MethodAttributes.HideBySig Or MethodAttributes.SpecialName _
                Or MethodAttributes.RTSpecialName)
        
        ' Add a field of type T, with the name Field.
        Dim myField As FieldBuilder = myType.DefineField( _
            "Field", typeParams(0), FieldAttributes.Public)
        
        ' Add a method and make it generic, with a type 
        ' parameter named U. Note how similar this is to 
        ' the way Sample is turned into a generic type. The
        ' method has no signature, because the type of its
        ' only parameter is U, which is not yet defined.
        Dim genMethod As MethodBuilder = _
            myType.DefineMethod("GM", _
                MethodAttributes.Public Or MethodAttributes.Static)
        Dim methodParamNames() As String = { "U" }
        Dim methodParams As GenericTypeParameterBuilder() = _
            genMethod.DefineGenericParameters(methodParamNames)

        ' Now add a signature for genMethod, specifying U
        ' as the type of the parameter. There is no return value
        ' and no custom modifiers.
        genMethod.SetSignature(Nothing, Nothing, Nothing, _
            New Type() { methodParams(0) }, Nothing, Nothing)
        
        ' Emit a method body for the generic method.
        Dim ilg As ILGenerator = genMethod.GetILGenerator()
        ' Construct the type Sample(Of U) using MakeGenericType.
        Dim SampleOfU As Type = _
            myType.MakeGenericType(methodParams(0))
        ' Create a local variable to store the instance of
        ' Sample(Of U).
        ilg.DeclareLocal(SampleOfU)
        ' Call the default constructor. Note that it is 
        ' necessary to have the default constructor for the
        ' constructed generic type Sample(Of U); use the 
        ' TypeBuilder.GetConstructor method to obtain this 
        ' constructor.
        Dim ctorOfU As ConstructorInfo = _
            TypeBuilder.GetConstructor(SampleOfU, ctor)
        ilg.Emit(OpCodes.Newobj, ctorOfU)
        ' Store the instance in the local variable; load it
        ' again, and load the parameter of genMethod.
        ilg.Emit(OpCodes.Stloc_0)
        ilg.Emit(OpCodes.Ldloc_0)
        ilg.Emit(OpCodes.Ldarg_0)
        ' In order to store the value in the field of the
        ' instance of Sample(Of U), it is necessary to have 
        ' a FieldInfo representing the field of the 
        ' constructed type. Use TypeBuilder.GetField to 
        ' obtain this FieldInfo.
        Dim FieldOfU As FieldInfo = _
            TypeBuilder.GetField(SampleOfU, myField)
        ' Store the value in the field. 
        ilg.Emit(OpCodes.Stfld, FieldOfU)
        ' Load the instance, load the field value, box it
        ' (specifying the type of the type parameter, U), 
        ' and print it.
        ilg.Emit(OpCodes.Ldloc_0)
        ilg.Emit(OpCodes.Ldfld, FieldOfU)
        ilg.Emit(OpCodes.Box, methodParams(0))
        Dim writeLineObj As MethodInfo = _
            GetType(Console).GetMethod("WriteLine", _
                New Type() {GetType(Object)})
        ilg.EmitCall(OpCodes.Call, writeLineObj, Nothing)
        ilg.Emit(OpCodes.Ret)
        
        ' Emit an entry point method; this must be in a
        ' non-generic type.
        Dim dummy As TypeBuilder = _
            myModule.DefineType("Dummy", _
                TypeAttributes.Class Or TypeAttributes.NotPublic)
        Dim entryPoint As MethodBuilder = _
            dummy.DefineMethod("Main", _
                MethodAttributes.Public Or MethodAttributes.Static, _
                Nothing, Nothing)
        ilg = entryPoint.GetILGenerator()
        ' In order to call the static generic method GM, it is
        ' necessary to create a constructed type from the 
        ' generic type definition for Sample. This can be ANY
        ' constructed type; in this case Sample(Of Integer)
        ' is used.
        Dim SampleOfInt As Type = _
            myType.MakeGenericType(GetType(Integer))
        ' Next get a MethodInfo representing the static generic
        ' method GM on type Sample(Of Integer).
        Dim SampleOfIntGM As MethodInfo = _
            TypeBuilder.GetMethod(SampleOfInt, genMethod)
        ' Next get a MethodInfo for GM(Of String), which is the 
        ' instantiation of generic method GM that is called
        ' by Sub Main.
        Dim GMOfString As MethodInfo = _
            SampleOfIntGM.MakeGenericMethod(GetType(String))
        ' Finally, emit the call. Push a string onto
        ' the stack, as the argument for the generic method.
        ilg.Emit(OpCodes.Ldstr, "Hello, world!")
        ilg.EmitCall(OpCodes.Call, GMOfString, Nothing)
        ilg.Emit(OpCodes.Ret)
        
        myType.CreateType()
        dummy.CreateType()
        myAssembly.SetEntryPoint(entryPoint)
        myAssembly.Save(myAsmName.Name & ".exe")
        
        Console.WriteLine(myAsmName.Name & ".exe has been saved.")
    
    End Sub 
End Class 

備註

GetConstructor方法提供一種方法來取得 ConstructorInfo 物件,該物件代表泛型型別定義由物件表示的結構化泛型型別的函式 TypeBuilderThe GetConstructor method provides a way to get a ConstructorInfo object that represents a constructor of a constructed generic type whose generic type definition is represented by a TypeBuilder object.

例如,假設您有一個 TypeBuilder 物件,代表 c # 語法中的型別 G<T> (G(Of T) 在 Visual Basic 的 generic <T> ref class G c + +) 和 ConstructorBuilder 代表之函式的物件 G<T>For example, suppose you have a TypeBuilder object that represents the type G<T> in C# syntax (G(Of T) in Visual Basic, generic <T> ref class G in C++) and a ConstructorBuilder object that represents a constructor of G<T>. 假設 G<T> 具有型別參數的泛型方法 U ,可建立所建立型別的實例 G<U>Suppose that G<T> has a generic method with type parameter U that creates an instance of the constructed type G<U>. 若要發出程式碼以建立所建立之型別的實例,您需要一個 ConstructorInfo 物件來表示此結構型別的函式(換句話說,它會建立的實例) G<U>In order to emit the code to create an instance of the constructed type, you need a ConstructorInfo object that represents the constructor of this constructed type - in other words, that creates an instance of G<U>. 若要這樣做,請先 MakeGenericType 在物件上呼叫方法 TypeBuilder ,並指定 GenericTypeParameterBuilder 代表 U 做為型別引數的物件。To do this, first call the MakeGenericType method on the TypeBuilder object, specifying the GenericTypeParameterBuilder object that represents U as the type argument. 然後以方法的傳回 GetConstructorMakeGenericType 作為參數 type ,以及 ConstructorBuilder 表示 as 參數之的函式的物件來呼叫方法 G<U> constructorThen call the GetConstructor method with the return value of the MakeGenericType method as parameter type and the ConstructorBuilder object that represents the constructor of G<U> as parameter constructor. 傳回值是 ConstructorInfo 您發出函式呼叫所需的物件。The return value is the ConstructorInfo object you need to emit the function call. 此程式碼範例會示範此案例。The code example demonstrates this scenario.

適用於