TypeBuilder.DefineConstructor Метод

Определение

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

Перегрузки

Имя Описание
DefineConstructor(MethodAttributes, CallingConventions, Type[])

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

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

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

DefineConstructor(MethodAttributes, CallingConventions, Type[])

Исходный код:
TypeBuilder.cs
Исходный код:
TypeBuilder.cs
Исходный код:
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().

Примеры

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

// 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
Исходный код:
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.

Комментарии

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

Note

Дополнительные сведения о пользовательских модификаторах см. в статьях ECMA C# и стандартных стандартах инфраструктуры clma-335 — инфраструктуре общего языка (CLI).

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