Поделиться через


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
Исходный код:
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);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]
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);
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);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)>]
member this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
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

Побитовое сочетание значений перечисления, указывающее, как выполняется поиск.

–или–

значение a

binder
Binder

Объект, который определяет набор свойств и включает привязку, которая может включать выбор перегруженного метода, приведение типов аргументов и вызов элемента через отражение.

–или–

Ссылка null (Nothing в Visual Basic) для использования DefaultBinder.

callConvention
CallingConventions

Объект, указывающий набор правил, используемых в отношении порядка и макета аргументов, как передается возвращаемое значение, какие регистры используются для аргументов, а стек очищается.

types
Type[]

Массив Type объектов, представляющих число, порядок и тип параметров для получения конструктора.

–или–

Пустой массив типа Type (т. е. type[] = new Type[0]) для получения конструктора, который не принимает параметров.

modifiers
ParameterModifier[]

Массив ParameterModifier объектов, представляющих атрибуты, связанные с соответствующим элементом в массиве types . Привязка по умолчанию не обрабатывает этот параметр.

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

Объект, представляющий конструктор, соответствующий указанным требованиям, при обнаружении; nullв противном случае .

Реализации

Атрибуты

Исключения

types равно null.

–или–

Одним из элементов является typesnull.

types является многомерным.

–или–

modifiers является многомерным.

–или–

types и modifiers не имеют той же длины.

Примеры

В следующем примере показано, как получить тип MyClassобъекта, получить ConstructorInfo объект и отобразить сигнатуру конструктора.

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.Instance, либо BindingFlags.Static.

  • Укажите BindingFlags.Public , чтобы включить открытые конструкторы в поиск.

  • Укажите BindingFlags.NonPublic , чтобы включить недоступные конструкторы (т. е. частные, внутренние и защищенные конструкторы) в поиск.

См. System.Reflection.BindingFlags для получения дополнительной информации.

Чтобы получить инициализатор класса (статический конструктор) с помощью этого метода, необходимо указать BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic в Visual Basic). Вы также можете получить инициализатор класса с помощью TypeInitializer свойства.

В следующей таблице показано, какие элементы базового класса возвращаются Get методами при отражении типа.

Тип участника Статический Нестатическое
Конструктор Нет Нет
Поле Нет Да. Поле всегда скрывается по имени и подписи.
Event Неприменимо Правило системы общего типа заключается в том, что наследование следует тем же правилам, что и методы, реализующие свойство. Отражение обрабатывает свойства как скрытие по имени и сигнатуре. См. примечание 2 ниже.
Метод Нет Да. Метод (виртуальный и не виртуальный) может быть скрыт по имени или как по имени, так и по подписи.
Вложенный тип Нет Нет
Недвижимость Неприменимо Правило системы общего типа заключается в том, что наследование следует тем же правилам, что и методы, реализующие свойство. Отражение обрабатывает свойства как скрытие по имени и сигнатуре. См. примечание 2 ниже.
  1. Скрытие по имени и сигнатуре учитывает все части подписи, включая настраиваемые модификаторы, возвращаемые типы, типы параметров, sentinels и неуправляемые соглашения о вызовах. Это двоичное сравнение.

  2. Для отражения свойства и события скрываются по имени и сигнатуре. Если у вас есть свойство с методами get и set в базовом классе, но производный класс имеет только метод get, свойство производного класса перекрывает свойство базового класса, и вы не сможете получить доступ к методу set в базовом классе.

  3. Пользовательские атрибуты не являются частью общей системы типов.

Замечание

Параметры нельзя опустить при поиске конструкторов и методов. При вызове можно опустить только параметры.

Если текущий Type представляет созданный универсальный тип, этот метод возвращает ConstructorInfo параметры типа, замененные соответствующими аргументами типа. Если текущий Type представляет параметр типа в определении универсального типа или универсального метода, этот метод всегда возвращается null.

См. также раздел

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

GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[])

Исходный код:
Type.cs
Исходный код:
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);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]
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);
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);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)>]
member this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
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

Побитовое сочетание значений перечисления, указывающее, как выполняется поиск.

–или–

значение a

binder
Binder

Объект, который определяет набор свойств и включает привязку, которая может включать выбор перегруженного метода, приведение типов аргументов и вызов элемента через отражение.

–или–

Ссылка null (Nothing в Visual Basic) для использования DefaultBinder.

types
Type[]

Массив Type объектов, представляющих число, порядок и тип параметров для получения конструктора.

–или–

Пустой массив типа Type (т. е. type[] = new Type[0]) для получения конструктора, который не принимает параметров.

–или–

EmptyTypes.

modifiers
ParameterModifier[]

Массив ParameterModifier объектов, представляющих атрибуты, связанные с соответствующим элементом в массиве типов параметров. Привязка по умолчанию не обрабатывает этот параметр.

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

ConstructorInfo Объект, представляющий конструктор, соответствующий указанным требованиям, если он найден; в противном случае null.

Реализации

Атрибуты

Исключения

types равно null.

–или–

Одним из элементов является typesnull.

types является многомерным.

–или–

modifiers является многомерным.

–или–

types и modifiers не имеют той же длины.

Примеры

В следующем примере показано, как получить тип MyClassобъекта, получить ConstructorInfo объект и отобразить сигнатуру конструктора.

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.Instance, либо BindingFlags.Static.

  • Укажите BindingFlags.Public , чтобы включить открытые конструкторы в поиск.

  • Укажите BindingFlags.NonPublic , чтобы включить недоступные конструкторы (т. е. частные, внутренние и защищенные конструкторы) в поиск.

См. System.Reflection.BindingFlags для получения дополнительной информации.

Чтобы получить инициализатор класса (статический конструктор) с помощью этой перегрузки метода, необходимо указать BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic в Visual Basic). Вы также можете получить инициализатор класса с помощью TypeInitializer свойства.

Замечание

Параметры нельзя опустить при поиске конструкторов и методов. При вызове можно опустить только параметры.

Если текущий Type представляет созданный универсальный тип, этот метод возвращает ConstructorInfo параметры типа, замененные соответствующими аргументами типа. Если текущий Type представляет параметр типа в определении универсального типа или универсального метода, этот метод всегда возвращается null.

См. также раздел

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

GetConstructor(BindingFlags, Type[])

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

Выполняет поиск конструктора, параметры которого соответствуют указанным типам аргументов, используя указанные ограничения привязки.

public:
 System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, cli::array <Type ^> ^ types);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]
public System.Reflection.ConstructorInfo? GetConstructor(System.Reflection.BindingFlags bindingAttr, Type[] types);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)>]
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 [] = Array.Empty{Type}()) для получения конструктора, который не принимает параметров. -или- EmptyTypes.

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

ConstructorInfo Объект, представляющий конструктор, соответствующий указанным требованиям, если он найден; в противном случае null.

Атрибуты

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

GetConstructor(Type[])

Исходный код:
Type.cs
Исходный код:
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);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]
public System.Reflection.ConstructorInfo? GetConstructor(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);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)>]
member this.GetConstructor : Type[] -> System.Reflection.ConstructorInfo
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 массив объектов, чтобы получить конструктор, который не принимает параметров. Такой пустой массив предоставляется полем staticEmptyTypes.

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

Объект, представляющий конструктор общедоступного экземпляра, параметры которого соответствуют типам в массиве типов параметров, если найдено; nullв противном случае .

Реализации

Атрибуты

Исключения

types равно null.

–или–

Одним из элементов является typesnull.

types является многомерным.

Примеры

В следующем примере показано, как получить тип MyClassобъекта, получить ConstructorInfo объект и отобразить сигнатуру конструктора.

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.

См. также раздел

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