Type.GetConstructor Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает определенный конструктор текущего объекта Type.
Перегрузки
| GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) |
Выполняет поиск конструктора с параметрами, соответствующими указанным модификаторам и типам аргументов, с учетом заданных ограничений по привязке и соглашений о вызовах. |
| GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[]) |
Выполняет поиск конструктора, параметры которого соответствуют указанным типам аргументов и модификаторам, используя заданные ограничения привязки. |
| GetConstructor(BindingFlags, Type[]) |
Выполняет поиск конструктора, параметры которого соответствуют указанным типам аргументов, используя указанные ограничения привязки. |
| GetConstructor(Type[]) |
Выполняет поиск открытого конструктора экземпляра, параметры которого соответствуют типам, содержащимся в указанном массиве. |
GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
Выполняет поиск конструктора с параметрами, соответствующими указанным модификаторам и типам аргументов, с учетом заданных ограничений по привязке и соглашений о вызовах.
public:
System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, System::Reflection::CallingConventions callConvention, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public:
virtual System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, System::Reflection::CallingConventions callConvention, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public System.Reflection.ConstructorInfo? GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.ConstructorInfo GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers);
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.ConstructorInfo GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers);
member this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
Public Function GetConstructor (bindingAttr As BindingFlags, binder As Binder, callConvention As CallingConventions, types As Type(), modifiers As ParameterModifier()) As ConstructorInfo
Параметры
- bindingAttr
- BindingFlags
Побитовое сочетание значений перечисления, указывающих способ проведения поиска.
-или-
Default для возврата null.
- binder
- Binder
Объект, определяющий набор свойств и разрешающий привязку, что может включать выбор перегруженных методов, приведение типов аргументов и вызов члена с помощью отражения.
-или-
Пустая ссылка (Nothing в Visual Basic) для использования свойства DefaultBinder.
- callConvention
- CallingConventions
Объект, определяющий набор применяемых правил, касающихся порядка и расположения аргументов, способа передачи возвращаемого значения, регистров, используемых для аргументов, и очистки стека.
- types
- Type[]
Массив объектов Type, предоставляющий число, порядок и тип параметров, извлекаемых конструктором.
-или-
Пустой массив объектов типа Type (то есть Type[] types = new Type[0]), если требуется получить конструктор, который не имеет параметров.
- modifiers
- ParameterModifier[]
Массив объектов ParameterModifier, представляющих атрибуты, связанные с соответствующим элементом в массиве types. Связыватель по умолчанию не обрабатывает этот параметр.
Возвращаемое значение
Если поиск выполнен удачно, возвращается объект, представляющий конструктор, который соответствует указанным требованиям; в противном случае возвращается значение null.
Реализации
- Атрибуты
Исключения
types имеет значение null.
-или-
Один из элементов в types имеет значение null.
Массив types является многомерным.
-или-
Массив modifiers является многомерным.
-или-
types и modifiers имеют разную длину.
Примеры
В следующем примере показано, как получить тип MyClass, получить ConstructorInfo объект и отобразить сигнатуру конструктора.
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyClass1
{
public:
MyClass1( int i ){}
};
int main()
{
try
{
Type^ myType = MyClass1::typeid;
array<Type^>^types = gcnew array<Type^>(1);
types[ 0 ] = int::typeid;
// Get the public instance constructor that takes an integer parameter.
ConstructorInfo^ constructorInfoObj = myType->GetConstructor( static_cast<BindingFlags>(BindingFlags::Instance | BindingFlags::Public), nullptr, CallingConventions::HasThis, types, nullptr );
if ( constructorInfoObj != nullptr )
{
Console::WriteLine( "The constructor of MyClass1 that is a public instance method and takes an integer as a parameter is: " );
Console::WriteLine( constructorInfoObj );
}
else
{
Console::WriteLine( "The constructor of MyClass1 that is a public instance method and takes an integer as a parameter is not available." );
}
}
catch ( ArgumentNullException^ e )
{
Console::WriteLine( "ArgumentNullException: {0}", e->Message );
}
catch ( ArgumentException^ e )
{
Console::WriteLine( "ArgumentException: {0}", e->Message );
}
catch ( SecurityException^ e )
{
Console::WriteLine( "SecurityException: {0}", e->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception: {0}", e->Message );
}
}
using System;
using System.Reflection;
using System.Security;
public class MyClass3
{
public MyClass3(int i) { }
public static void Main()
{
try
{
Type myType = typeof(MyClass3);
Type[] types = new Type[1];
types[0] = typeof(int);
// Get the public instance constructor that takes an integer parameter.
ConstructorInfo constructorInfoObj = myType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public, null,
CallingConventions.HasThis, types, null);
if (constructorInfoObj != null)
{
Console.WriteLine("The constructor of MyClass3 that is a public " +
"instance method and takes an integer as a parameter is: ");
Console.WriteLine(constructorInfoObj.ToString());
}
else
{
Console.WriteLine("The constructor of MyClass3 that is a public instance " +
"method and takes an integer as a parameter is not available.");
}
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: " + e.Message);
}
catch (ArgumentException e)
{
Console.WriteLine("ArgumentException: " + e.Message);
}
catch (SecurityException e)
{
Console.WriteLine("SecurityException: " + e.Message);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
}
open System
open System.Reflection
open System.Security
type MyClass1(i: int) = class end
try
let myType = typeof<MyClass1>
let types = [| typeof<int> |]
// Get the public instance constructor that takes an integer parameter.
let constructorInfoObj = myType.GetConstructor(BindingFlags.Instance ||| BindingFlags.Public, null, CallingConventions.HasThis, types, null)
if constructorInfoObj <> null then
printfn "The constructor of MyClass1 that is a public instance method and takes an integer as a parameter is: \n{constructorInfoObj}"
else
printfn "The constructor of MyClass1 that is a public instance method and takes an integer as a parameter is not available."
with
| :? ArgumentNullException as e ->
printfn $"ArgumentNullException: {e.Message}"
| :? ArgumentException as e ->
printfn $"ArgumentException: {e.Message}"
| :? SecurityException as e ->
printfn $"SecurityException: {e.Message}"
| e ->
printfn $"Exception: {e.Message}"
Public Class MyClass1
Public Sub New(ByVal i As Integer)
End Sub
Public Shared Sub Main()
Try
Dim myType As Type = GetType(MyClass1)
Dim types(0) As Type
types(0) = GetType(Integer)
' Get the public instance constructor that takes an integer parameter.
Dim constructorInfoObj As ConstructorInfo = _
myType.GetConstructor(BindingFlags.Instance Or _
BindingFlags.Public, Nothing, _
CallingConventions.HasThis, types, Nothing)
If Not (constructorInfoObj Is Nothing) Then
Console.WriteLine("The constructor of MyClass1 that " + _
"is a public instance method and takes an " + _
"integer as a parameter is: ")
Console.WriteLine(constructorInfoObj.ToString())
Else
Console.WriteLine("The constructor MyClass1 that " + _
"is a public instance method and takes an " + _
"integer as a parameter is not available.")
End If
Catch e As ArgumentNullException
Console.WriteLine("ArgumentNullException: " + e.Message)
Catch e As ArgumentException
Console.WriteLine("ArgumentException: " + e.Message)
Catch e As SecurityException
Console.WriteLine("SecurityException: " + e.Message)
Catch e As Exception
Console.WriteLine("Exception: " + e.Message)
End Try
End Sub
End Class
Комментарии
Хотя связыватель по умолчанию не обрабатывает ParameterModifier ( modifiers параметр ), можно использовать абстрактный System.Reflection.Binder класс для записи пользовательского связывателя, который обрабатывает modifiers.
ParameterModifier используется только при вызове через COM-взаимодействие, и обрабатываются только параметры, передаваемые по ссылке.
Если точное совпадение не существует, binder будет пытаться привить типы параметров, указанные в массиве types , чтобы выбрать совпадение. Если не binder удается выбрать совпадение, возвращается null значение .
BindingFlags Следующие флаги фильтра можно использовать для определения конструкторов, которые следует включить в поиск:
Для получения возврата необходимо указать или
BindingFlags.InstanceBindingFlags.Static.Укажите
BindingFlags.Public, чтобы включить открытые конструкторы в поиск.Укажите
BindingFlags.NonPublic, чтобы включить в поиск не являющиеся открытыми конструкторы (частные, внутренние и защищенные конструкторы).
Дополнительные сведения см. в разделе System.Reflection.BindingFlags.
Чтобы получить инициализатор класса (статический конструктор) с помощью этого метода, необходимо указать BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic в Visual Basic). Вы также можете получить инициализатор класса с помощью TypeInitializer свойства .
В следующей таблице показано, какие члены базового класса возвращаются методами Get при отражении в типе.
| Тип члена | Статические | Нестатическое |
|---|---|---|
| Конструктор | Нет | Нет |
| Поле | Нет | Да. Поле всегда имеет значение hide-by-name-and-signature. |
| Событие | Неприменимо | Общее правило системы типов состоит в том, что наследование совпадает с наследованием методов, реализующих свойство . Отражение рассматривает свойства как скрытие по имени и сигнатуре. См. примечание 2 ниже. |
| Метод | Нет | Да. Метод (как виртуальный, так и не виртуальный) может иметь значение hide-by-name или hide-by-name-and-signature. |
| Вложенный тип | Нет | Нет |
| Свойство. | Неприменимо | Общее правило системы типов состоит в том, что наследование совпадает с наследованием методов, реализующих свойство . Отражение рассматривает свойства как скрытие по имени и сигнатуре. См. примечание 2 ниже. |
Функция скрытия по имени и подписи учитывает все части сигнатуры, включая пользовательские модификаторы, типы возвращаемых значений, типы параметров, sentinels и неуправляемые соглашения о вызовах. Это двоичное сравнение.
Для отражения свойства и события представляют собой скрытие по имени и сигнатуре. Если у вас есть свойство с методом доступа get и set в базовом классе, но производный класс имеет только метод доступа get, свойство производного класса скрывает свойство базового класса, и вы не сможете получить доступ к методу задания в базовом классе.
Настраиваемые атрибуты не являются частью системы общих типов.
Примечание
Нельзя опускать параметры при поиске конструкторов и методов. Параметры можно опустить только при вызове .
Если текущий Type представляет сконструированный универсальный тип, этот метод возвращает ConstructorInfo с параметрами типа, замененными соответствующими аргументами типа. Если текущий Type объект представляет параметр типа в определении универсального типа или универсального метода, этот метод всегда возвращает значение null.
См. также раздел
- ConstructorInfo
- BindingFlags
- Binder
- DefaultBinder
- CallingConventions
- ParameterModifier
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()
Применяется к
GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[])
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
Выполняет поиск конструктора, параметры которого соответствуют указанным типам аргументов и модификаторам, используя заданные ограничения привязки.
public:
System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public:
virtual System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public System.Reflection.ConstructorInfo? GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.ConstructorInfo GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers);
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.ConstructorInfo GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers);
member this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
Public Function GetConstructor (bindingAttr As BindingFlags, binder As Binder, types As Type(), modifiers As ParameterModifier()) As ConstructorInfo
Параметры
- bindingAttr
- BindingFlags
Побитовое сочетание значений перечисления, указывающих способ проведения поиска.
-или-
Default для возврата null.
- binder
- Binder
Объект, определяющий набор свойств и разрешающий привязку, что может включать выбор перегруженных методов, приведение типов аргументов и вызов члена с помощью отражения.
-или-
Пустая ссылка (Nothing в Visual Basic) для использования свойства DefaultBinder.
- types
- Type[]
Массив объектов Type, предоставляющий число, порядок и тип параметров, извлекаемых конструктором.
-или-
Пустой массив объектов типа Type (то есть Type[] types = new Type[0]), если требуется получить конструктор, который не имеет параметров.
-или-
- modifiers
- ParameterModifier[]
Массив объектов ParameterModifier, представляющих атрибуты, связанные с соответствующим элементом в массиве типов параметра. Связыватель по умолчанию не обрабатывает этот параметр.
Возвращаемое значение
Если поиск выполнен удачно, возвращается объект ConstructorInfo, представляющий конструктор, который соответствует указанным требованиям; в противном случае возвращается значение null.
Реализации
- Атрибуты
Исключения
types имеет значение null.
-или-
Один из элементов в types имеет значение null.
Массив types является многомерным.
-или-
Массив modifiers является многомерным.
-или-
types и modifiers имеют разную длину.
Примеры
В следующем примере показано, как получить тип MyClass, получить ConstructorInfo объект и отобразить сигнатуру конструктора.
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyClass1
{
public:
MyClass1( int i ){}
};
int main()
{
try
{
Type^ myType = MyClass1::typeid;
array<Type^>^types = gcnew array<Type^>(1);
types[ 0 ] = int::typeid;
// Get the constructor that is public and takes an integer parameter.
ConstructorInfo^ constructorInfoObj = myType->GetConstructor( static_cast<BindingFlags>(BindingFlags::Instance | BindingFlags::Public), nullptr, types, nullptr );
if ( constructorInfoObj != nullptr )
{
Console::WriteLine( "The constructor of MyClass1 that is public and takes an integer as a parameter is:" );
Console::WriteLine( constructorInfoObj );
}
else
{
Console::WriteLine( "The constructor of the MyClass1 that is public and takes an integer as a parameter is not available." );
}
}
catch ( ArgumentNullException^ e )
{
Console::WriteLine( "ArgumentNullException: {0}", e->Message );
}
catch ( ArgumentException^ e )
{
Console::WriteLine( "ArgumentException: {0}", e->Message );
}
catch ( SecurityException^ e )
{
Console::WriteLine( "SecurityException: {0}", e->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception: {0}", e->Message );
}
}
using System;
using System.Reflection;
using System.Security;
public class MyClass2
{
public MyClass2(int i) { }
public static void Main()
{
try
{
Type myType = typeof(MyClass2);
Type[] types = new Type[1];
types[0] = typeof(int);
// Get the constructor that is public and takes an integer parameter.
ConstructorInfo constructorInfoObj = myType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public, null, types, null);
if (constructorInfoObj != null)
{
Console.WriteLine("The constructor of MyClass2 that is public " +
"and takes an integer as a parameter is:");
Console.WriteLine(constructorInfoObj.ToString());
}
else
{
Console.WriteLine("The constructor of the MyClass2 that is public " +
"and takes an integer as a parameter is not available.");
}
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: " + e.Message);
}
catch (ArgumentException e)
{
Console.WriteLine("ArgumentException: " + e.Message);
}
catch (SecurityException e)
{
Console.WriteLine("SecurityException: " + e.Message);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
}
open System
open System.Reflection
open System.Security
type MyClass1(i: int) = class end
try
let myType = typeof<MyClass1>
let types = [| typeof<int> |]
// Get the constructor that is public and takes an integer parameter.
let constructorInfoObj = myType.GetConstructor(BindingFlags.Instance ||| BindingFlags.Public, null, types, null)
if constructorInfoObj <> null then
printfn "The constructor of MyClass1 that is public and takes an integer as a parameter is:\n{constructorInfoObj}"
else
printfn "The constructor of the MyClass1 that is public and takes an integer as a parameter is not available."
with
| :? ArgumentNullException as e ->
printfn $"ArgumentNullException: {e.Message}"
| :? ArgumentException as e ->
printfn $"ArgumentException: {e.Message}"
| :? SecurityException as e ->
printfn $"SecurityException: {e.Message}"
| e ->
printfn $"Exception: {e.Message}"
Imports System.Reflection
Imports System.Security
Public Class MyClass1
Public Sub New(ByVal i As Integer)
End Sub
Public Shared Sub Main()
Try
Dim myType As Type = GetType(MyClass1)
Dim types(0) As Type
types(0) = GetType(Integer)
' Get the constructor that is public and takes an integer parameter.
Dim constructorInfoObj As ConstructorInfo = _
myType.GetConstructor(BindingFlags.Instance Or _
BindingFlags.Public, Nothing, types, Nothing)
If Not (constructorInfoObj Is Nothing) Then
Console.WriteLine("The constructor of MyClass1 that is " + _
"public and takes an integer as a parameter is ")
Console.WriteLine(constructorInfoObj.ToString())
Else
Console.WriteLine("The constructor of MyClass1 that is " + _
"public and takes an integer as a parameter is not available.")
End If
Catch e As ArgumentNullException
Console.WriteLine("ArgumentNullException: " + e.Message)
Catch e As ArgumentException
Console.WriteLine("ArgumentException: " + e.Message)
Catch e As SecurityException
Console.WriteLine("SecurityException: " + e.Message)
Catch e As Exception
Console.WriteLine("Exception: " + e.Message)
End Try
End Sub
End Class
Комментарии
Если точное совпадение не существует, binder будет пытаться привить типы параметров, указанные в массиве types , чтобы выбрать совпадение. Если не binder удается выбрать совпадение, возвращается null значение .
BindingFlags Следующие флаги фильтра можно использовать для определения конструкторов, которые следует включить в поиск:
Для получения возврата необходимо указать или
BindingFlags.InstanceBindingFlags.Static.Укажите
BindingFlags.Public, чтобы включить открытые конструкторы в поиск.Укажите
BindingFlags.NonPublic, чтобы включить в поиск не являющиеся открытыми конструкторы (частные, внутренние и защищенные конструкторы).
Дополнительные сведения см. в разделе System.Reflection.BindingFlags.
Чтобы получить инициализатор класса (статический конструктор) с помощью этой перегрузки метода, необходимо указать BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic в Visual Basic). Вы также можете получить инициализатор класса с помощью TypeInitializer свойства .
Примечание
Нельзя опускать параметры при поиске конструкторов и методов. Параметры можно опустить только при вызове .
Если текущий Type представляет сконструированный универсальный тип, этот метод возвращает ConstructorInfo с параметрами типа, замененными соответствующими аргументами типа. Если текущий Type объект представляет параметр типа в определении универсального типа или универсального метода, этот метод всегда возвращает значение null.
См. также раздел
- ConstructorInfo
- BindingFlags
- Binder
- DefaultBinder
- ParameterModifier
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()
Применяется к
GetConstructor(BindingFlags, Type[])
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
Выполняет поиск конструктора, параметры которого соответствуют указанным типам аргументов, используя указанные ограничения привязки.
public:
System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, cli::array <Type ^> ^ types);
public System.Reflection.ConstructorInfo? GetConstructor(System.Reflection.BindingFlags bindingAttr, Type[] types);
member this.GetConstructor : System.Reflection.BindingFlags * Type[] -> System.Reflection.ConstructorInfo
Public Function GetConstructor (bindingAttr As BindingFlags, types As Type()) As ConstructorInfo
Параметры
- bindingAttr
- BindingFlags
Побитовое сочетание значений перечисления, указывающих способ проведения поиска.
-или- По умолчанию возвращается nullзначение .
- types
- Type[]
Массив объектов Type, представляющих число, порядок и тип параметров для получения конструктором. -или- Пустой массив типа Type (то есть Type[] types = Array.Empty{Type}()) для получения конструктора, не принимающего параметров. -или- EmptyTypes.
Возвращаемое значение
Если поиск выполнен удачно, возвращается объект ConstructorInfo, представляющий конструктор, который соответствует указанным требованиям; в противном случае возвращается значение null.
Применяется к
GetConstructor(Type[])
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
- Исходный код:
- Type.cs
Выполняет поиск открытого конструктора экземпляра, параметры которого соответствуют типам, содержащимся в указанном массиве.
public:
System::Reflection::ConstructorInfo ^ GetConstructor(cli::array <Type ^> ^ types);
public:
virtual System::Reflection::ConstructorInfo ^ GetConstructor(cli::array <Type ^> ^ types);
public System.Reflection.ConstructorInfo? GetConstructor(Type[] types);
public System.Reflection.ConstructorInfo GetConstructor(Type[] types);
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.ConstructorInfo GetConstructor(Type[] types);
member this.GetConstructor : Type[] -> System.Reflection.ConstructorInfo
abstract member GetConstructor : Type[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : Type[] -> System.Reflection.ConstructorInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
abstract member GetConstructor : Type[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : Type[] -> System.Reflection.ConstructorInfo
Public Function GetConstructor (types As Type()) As ConstructorInfo
Параметры
- types
- Type[]
Массив объектов Type, предоставляющих число, порядок и тип параметров нужного конструктора.
-или-
Пустой массив объектов Type для получения конструктора, не имеющего параметров. Подобный пустой массив предоставляется полем static с описателем EmptyTypes.
Возвращаемое значение
Объект, представляющий открытый конструктор экземпляра, параметры которого соответствуют типам, указанным в массиве типов параметров, если такой конструктор найден; в противном случае — null.
Реализации
- Атрибуты
Исключения
types имеет значение null.
-или-
Один из элементов в types имеет значение null.
Массив types является многомерным.
Примеры
В следующем примере показано, как получить тип MyClass, получить ConstructorInfo объект и отобразить сигнатуру конструктора.
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyClass1
{
public:
MyClass1(){}
MyClass1( int i ){}
};
int main()
{
try
{
Type^ myType = MyClass1::typeid;
array<Type^>^types = gcnew array<Type^>(1);
types[ 0 ] = int::typeid;
// Get the constructor that takes an integer as a parameter.
ConstructorInfo^ constructorInfoObj = myType->GetConstructor( types );
if ( constructorInfoObj != nullptr )
{
Console::WriteLine( "The constructor of MyClass1 that takes an integer as a parameter is: " );
Console::WriteLine( constructorInfoObj );
}
else
{
Console::WriteLine( "The constructor of MyClass1 that takes an integer as a parameter is not available." );
}
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception caught." );
Console::WriteLine( "Source: {0}", e->Source );
Console::WriteLine( "Message: {0}", e->Message );
}
}
using System;
using System.Reflection;
public class MyClass1
{
public MyClass1() { }
public MyClass1(int i) { }
public static void Main()
{
try
{
Type myType = typeof(MyClass1);
Type[] types = new Type[1];
types[0] = typeof(int);
// Get the constructor that takes an integer as a parameter.
ConstructorInfo constructorInfoObj = myType.GetConstructor(types);
if (constructorInfoObj != null)
{
Console.WriteLine("The constructor of MyClass1 that takes an " +
"integer as a parameter is: ");
Console.WriteLine(constructorInfoObj.ToString());
}
else
{
Console.WriteLine("The constructor of MyClass1 that takes an integer " +
"as a parameter is not available.");
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught.");
Console.WriteLine("Source: " + e.Source);
Console.WriteLine("Message: " + e.Message);
}
}
}
type MyClass1() =
new (i: int) = MyClass1()
try
let myType = typeof<MyClass1>
let types = [| typeof<int> |]
// Get the constructor that takes an integer as a parameter.
let constructorInfoObj = myType.GetConstructor types
if constructorInfoObj <> null then
printfn "The constructor of MyClass1 that takes an integer as a parameter is: \n{constructorInfoObj}"
else
printfn "The constructor of MyClass1 that takes an integer as a parameter is not available."
with e ->
printfn "Exception caught."
printfn $"Source: {e.Source}"
printfn $"Message: {e.Message}"
Imports System.Reflection
Imports System.Security
Public Class MyClass1
Public Sub New()
End Sub
Public Sub New(ByVal i As Integer)
End Sub
Public Shared Sub Main()
Try
Dim myType As Type = GetType(MyClass1)
Dim types(0) As Type
types(0) = GetType(Int32)
' Get the constructor that takes an integer as a parameter.
Dim constructorInfoObj As ConstructorInfo = myType.GetConstructor(types)
If Not (constructorInfoObj Is Nothing) Then
Console.WriteLine("The constructor of MyClass that takes an integer as a parameter is: ")
Console.WriteLine(constructorInfoObj.ToString())
Else
Console.WriteLine("The constructor of MyClass that takes no " + "parameters is not available.")
End If
Catch e As Exception
Console.WriteLine("Exception caught.")
Console.WriteLine(("Source: " + e.Source))
Console.WriteLine(("Message: " + e.Message))
End Try
End Sub
End Class
Комментарии
Эта перегрузка метода ищет конструкторы открытых экземпляров и не может использоваться для получения инициализатора класса (статический конструктор). Чтобы получить инициализатор класса, используйте перегрузку, которая принимает BindingFlags, и укажите | BindingFlags.NonPublicBindingFlags.Static(BindingFlags.StaticOrBindingFlags.NonPublic в Visual Basic). Вы также можете получить инициализатор класса с помощью TypeInitializer свойства .
Если запрошенный конструктор не является открытым, этот метод возвращает null.
Примечание
Нельзя опускать параметры при поиске конструкторов и методов. Параметры можно опустить только при вызове .
Если текущий Type представляет сконструированный универсальный тип, этот метод возвращает ConstructorInfo с параметрами типа, замененными соответствующими аргументами типа. Если текущий Type объект представляет параметр типа в определении универсального типа или универсального метода, этот метод всегда возвращает значение null.
См. также раздел
- ConstructorInfo
- DefaultBinder
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()