TypeBuilder.DefineConstructor Метод

Определение

Добавляет новый конструктор в динамический тип.

Перегрузки

DefineConstructor(MethodAttributes, CallingConventions, Type[])

Добавляет в тип новый конструктор с заданными атрибутами и сигнатурой.

DefineConstructor(MethodAttributes, CallingConventions, Type[], Type[][], Type[][])

Добавляет в тип новый конструктор с заданными атрибутами, сигнатурой и настраиваемыми модификаторами.

DefineConstructor(MethodAttributes, CallingConventions, Type[])

Исходный код:
TypeBuilder.cs
Исходный код:
TypeBuilder.cs
Исходный код:
TypeBuilder.cs

Добавляет в тип новый конструктор с заданными атрибутами и сигнатурой.

public:
 System::Reflection::Emit::ConstructorBuilder ^ DefineConstructor(System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, cli::array <Type ^> ^ parameterTypes);
public System.Reflection.Emit.ConstructorBuilder DefineConstructor (System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type[]? parameterTypes);
public System.Reflection.Emit.ConstructorBuilder DefineConstructor (System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type[] parameterTypes);
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.Emit.ConstructorBuilder DefineConstructor (System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type[] parameterTypes);
member this.DefineConstructor : System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type[] -> System.Reflection.Emit.ConstructorBuilder
[<System.Runtime.InteropServices.ComVisible(true)>]
member this.DefineConstructor : System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type[] -> System.Reflection.Emit.ConstructorBuilder
Public Function DefineConstructor (attributes As MethodAttributes, callingConvention As CallingConventions, parameterTypes As Type()) As ConstructorBuilder

Параметры

attributes
MethodAttributes

Атрибуты конструктора.

callingConvention
CallingConventions

Соглашение о вызовах конструктора.

parameterTypes
Type[]

Типы параметров конструктора.

Возвращаемое значение

Определенный конструктор.

Атрибуты

Исключения

Этот тип был создан ранее с помощью CreateType().

Примеры

В следующем примере кода демонстрируется использование для задания конкретной сигнатуры и атрибутов конструктора для динамического типа и возврата соответствующего DefineConstructorConstructorBuilder для заполнения MSIL.

// Define the constructor.
array<Type^>^ constructorArgs = {String::typeid};
ConstructorBuilder^ myConstructorBuilder =
   helloWorldTypeBuilder->DefineConstructor( MethodAttributes::Public,
      CallingConventions::Standard, constructorArgs );
// Generate IL for the method. The constructor stores its argument in the private field.
ILGenerator^ myConstructorIL = myConstructorBuilder->GetILGenerator();
myConstructorIL->Emit( OpCodes::Ldarg_0 );
myConstructorIL->Emit( OpCodes::Ldarg_1 );
myConstructorIL->Emit( OpCodes::Stfld, myGreetingField );
myConstructorIL->Emit( OpCodes::Ret );
// Define the constructor.
Type[] constructorArgs = { typeof(String) };
ConstructorBuilder myConstructorBuilder =
   helloWorldTypeBuilder.DefineConstructor(MethodAttributes.Public,
                      CallingConventions.Standard, constructorArgs);
// Generate IL for the method. The constructor stores its argument in the private field.
ILGenerator myConstructorIL = myConstructorBuilder.GetILGenerator();
myConstructorIL.Emit(OpCodes.Ldarg_0);
myConstructorIL.Emit(OpCodes.Ldarg_1);
myConstructorIL.Emit(OpCodes.Stfld, myGreetingField);
myConstructorIL.Emit(OpCodes.Ret);
' Define the constructor.
Dim constructorArgs As Type() = {GetType(String)}
Dim myConstructorBuilder As ConstructorBuilder = helloWorldTypeBuilder.DefineConstructor _
                     (MethodAttributes.Public, CallingConventions.Standard, constructorArgs)
' Generate IL for the method. The constructor stores its argument in the private field.
Dim myConstructorIL As ILGenerator = myConstructorBuilder.GetILGenerator()
myConstructorIL.Emit(OpCodes.Ldarg_0)
myConstructorIL.Emit(OpCodes.Ldarg_1)
myConstructorIL.Emit(OpCodes.Stfld, myGreetingField)
myConstructorIL.Emit(OpCodes.Ret)

Комментарии

Если конструктор для динамического типа не определен, конструктор без параметров предоставляется автоматически и вызывает конструктор без параметров базового класса.

Если вы определяете конструктор для динамического типа, конструктор без параметров не предоставляется. В дополнение к определенному конструктору можно предоставить конструктор без параметров:

  • Если требуется конструктор без параметров, который просто вызывает конструктор без параметров базового класса, можно использовать DefineDefaultConstructor метод , чтобы создать его (и при необходимости ограничить доступ к нему). Не предоставляйте реализацию для этого конструктора без параметров. В этом случае при попытке использовать конструктор возникает исключение. При вызове CreateType метода исключение не возникает.

  • Если вам нужен конструктор без параметров, который выполняет нечто большее, чем просто вызов конструктора без параметров базового класса или вызывает другой конструктор базового класса или выполняет что-то совсем другое, необходимо использовать TypeBuilder.DefineConstructor метод , чтобы создать его и предоставить собственную реализацию.

Применяется к

DefineConstructor(MethodAttributes, CallingConventions, Type[], Type[][], Type[][])

Исходный код:
TypeBuilder.cs
Исходный код:
TypeBuilder.cs
Исходный код:
TypeBuilder.cs

Добавляет в тип новый конструктор с заданными атрибутами, сигнатурой и настраиваемыми модификаторами.

public:
 System::Reflection::Emit::ConstructorBuilder ^ DefineConstructor(System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, cli::array <Type ^> ^ parameterTypes, cli::array <cli::array <Type ^> ^> ^ requiredCustomModifiers, cli::array <cli::array <Type ^> ^> ^ optionalCustomModifiers);
public System.Reflection.Emit.ConstructorBuilder DefineConstructor (System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type[]? parameterTypes, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers);
public System.Reflection.Emit.ConstructorBuilder DefineConstructor (System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers);
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.Emit.ConstructorBuilder DefineConstructor (System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers);
member this.DefineConstructor : System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type[] * Type[][] * Type[][] -> System.Reflection.Emit.ConstructorBuilder
[<System.Runtime.InteropServices.ComVisible(true)>]
member this.DefineConstructor : System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type[] * Type[][] * Type[][] -> System.Reflection.Emit.ConstructorBuilder
Public Function DefineConstructor (attributes As MethodAttributes, callingConvention As CallingConventions, parameterTypes As Type(), requiredCustomModifiers As Type()(), optionalCustomModifiers As Type()()) As ConstructorBuilder

Параметры

attributes
MethodAttributes

Атрибуты конструктора.

callingConvention
CallingConventions

Соглашение о вызовах конструктора.

parameterTypes
Type[]

Типы параметров конструктора.

requiredCustomModifiers
Type[][]

Массив массивов типов. Каждый массив типов представляет обязательные настраиваемые модификаторы для соответствующего параметра, такие как IsConst. Если определенный параметр не имеет обязательных настраиваемых модификаторов, укажите null вместо массива массивов. Если ни один из параметров не имеет обязательных настраиваемых модификаторов, укажите null вместо массива массивов.

optionalCustomModifiers
Type[][]

Массив массивов типов. Каждый массив типов представляет необязательные настраиваемые модификаторы для соответствующего параметра, такие как IsConst. Если определенный параметр не имеет необязательных настраиваемых модификаторов, укажите null вместо массива массивов. Если ни один из параметров не имеет необязательных настраиваемых модификаторов, укажите null вместо массива типов.

Возвращаемое значение

Определенный конструктор.

Атрибуты

Исключения

Размер requiredCustomModifiers или optionalCustomModifiers не равен размеру parameterTypes.

Этот тип был создан ранее с помощью CreateType().

-или-

Для текущего динамического типа свойство IsGenericType имеет значение true, но свойство IsGenericTypeDefinition имеет значение false.

Комментарии

Эта перегрузка предоставляется для конструкторов управляемых компиляторов.

Примечание

Дополнительные сведения о настраиваемых модификаторах см. в разделах EcMA C# и Common Language Infrastructure Standards and Standard ECMA-335 — COMMON Language Infrastructure (CLI).

Применяется к