Partilhar via


Type.GetConstructor Método

Definição

Obtém um construtor específico do atual Type.

Sobrecargas

Nome Description
GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Pesquisa um construtor cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de associação especificadas e a convenção de chamada especificada.

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

Pesquisa um construtor cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de associação especificadas.

GetConstructor(BindingFlags, Type[])

Pesquisa um construtor cujos parâmetros correspondem aos tipos de argumento especificados, usando as restrições de associação especificadas.

GetConstructor(Type[])

Pesquisa um construtor de instância pública cujos parâmetros correspondem aos tipos na matriz especificada.

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

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Pesquisa um construtor cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de associação especificadas e a convenção de chamada especificada.

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

Parâmetros

bindingAttr
BindingFlags

Uma combinação bit a bit dos valores de enumeração que especificam como a pesquisa é conduzida.

- ou -

Default para retornar null.

binder
Binder

Um objeto que define um conjunto de propriedades e habilita a associação, que pode envolver a seleção de um método sobrecarregado, a coerção de tipos de argumento e a invocação de um membro por meio da reflexão.

- ou -

Uma referência nula (Nothing no Visual Basic), para usar o DefaultBinder.

callConvention
CallingConventions

O objeto que especifica o conjunto de regras a ser usado em relação à ordem e layout dos argumentos, como o valor retornado é passado, quais registros são usados para argumentos e a pilha é limpa.

types
Type[]

Uma matriz de Type objetos que representa o número, a ordem e o tipo dos parâmetros para o construtor obter.

- ou -

Uma matriz vazia do tipo Type (ou seja, Tipos[] = novo Tipo[0]) para obter um construtor que não usa parâmetros.

modifiers
ParameterModifier[]

Uma matriz de ParameterModifier objetos que representa os atributos associados ao elemento correspondente na types matriz. O associador padrão não processa esse parâmetro.

Retornos

Um objeto que representa o construtor que corresponde aos requisitos especificados, se encontrado; caso contrário, null.

Implementações

Atributos

Exceções

types é null.

- ou -

Um dos elementos é typesnull.

types é multidimensional.

- ou -

modifiers é multidimensional.

- ou -

types e modifiers não têm o mesmo comprimento.

Exemplos

O exemplo a seguir obtém o tipo de MyClass, obtém o ConstructorInfo objeto e exibe a assinatura do construtor.

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

Comentários

Embora o associador padrão não processe ParameterModifier (o modifiers parâmetro), você pode usar a classe abstrata System.Reflection.Binder para gravar um associador personalizado que processa modifiers. ParameterModifier é usado apenas durante a chamada por meio da interoperabilidade COM e apenas os parâmetros passados por referência são manipulados.

Se uma correspondência exata não existir, tentará binder coagir os tipos de parâmetro especificados na types matriz para selecionar uma correspondência. Se não binder for possível selecionar uma correspondência, será null retornado.

Os seguintes BindingFlags sinalizadores de filtro podem ser usados para definir quais construtores incluir na pesquisa:

  • Você deve especificar ou BindingFlags.Instance ou BindingFlags.Static para obter um retorno.

  • Especifique BindingFlags.Public para incluir construtores públicos na pesquisa.

  • Especifique BindingFlags.NonPublic para incluir construtores não públicos (ou seja, construtores privados, internos e protegidos) na pesquisa.

Consulte System.Reflection.BindingFlags para obter mais informações.

Para obter o inicializador de classe (construtor estático) usando esse método, você deve especificar BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic no Visual Basic). Você também pode obter o inicializador de classe usando a TypeInitializer propriedade.

A tabela a seguir mostra quais membros de uma classe base são retornados pelos métodos Get ao refletir sobre um tipo.

Tipo de Membro Estático Não estático
Construtor No No
Campo No Sim. Um campo permanece sempre oculto por nome e assinatura.
Acontecimento Não aplicável A regra de sistema do tipo comum é que a herança é a mesma dos métodos que implementam a propriedade. A reflexão trata as propriedades como hide-by-name-and-signature. Veja a observação 2 abaixo.
Método No Sim. Um método (virtual e não virtual) pode permanecer oculto por nome ou por nome e assinatura.
Tipo aninhado No No
Propriedade Não aplicável A regra de sistema do tipo comum é que a herança é a mesma dos métodos que implementam a propriedade. A reflexão trata as propriedades como hide-by-name-and-signature. Veja a observação 2 abaixo.
  1. Oculto por nome e assinatura considera todas as partes da assinatura, inclusive modificadores personalizados, tipos de retorno, tipos de parâmetro, sentinelas e convenções de chamada não gerenciadas. Essa é uma comparação binária.

  2. Para reflexão, propriedades e eventos permanecem ocultos por nome e assinatura. Se você tiver uma propriedade com um acessador get e um set na classe base, mas a classe derivada tiver apenas um acessador get, a propriedade de classe derivada ocultará a propriedade de classe base e você não poderá acessar o setter na classe base.

  3. Atributos personalizados não fazem parte do sistema de tipos comuns.

Observação

Você não pode omitir parâmetros ao procurar construtores e métodos. Você só pode omitir parâmetros ao invocar.

Se o atual Type representar um tipo genérico construído, este método retorna o ConstructorInfo com os parâmetros de tipo substituídos pelos argumentos de tipo apropriados. Se a corrente Type representar um parâmetro de tipo na definição de um tipo genérico ou método genérico, esse método sempre retornará null.

Confira também

Aplica-se a

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

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Pesquisa um construtor cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de associação especificadas.

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

Parâmetros

bindingAttr
BindingFlags

Uma combinação bit a bit dos valores de enumeração que especificam como a pesquisa é conduzida.

- ou -

Default para retornar null.

binder
Binder

Um objeto que define um conjunto de propriedades e habilita a associação, que pode envolver a seleção de um método sobrecarregado, a coerção de tipos de argumento e a invocação de um membro por meio da reflexão.

- ou -

Uma referência nula (Nothing no Visual Basic), para usar o DefaultBinder.

types
Type[]

Uma matriz de Type objetos que representa o número, a ordem e o tipo dos parâmetros para o construtor obter.

- ou -

Uma matriz vazia do tipo Type (ou seja, Tipos[] = novo Tipo[0]) para obter um construtor que não usa parâmetros.

- ou -

EmptyTypes.

modifiers
ParameterModifier[]

Uma matriz de ParameterModifier objetos que representa os atributos associados ao elemento correspondente na matriz de tipo de parâmetro. O associador padrão não processa esse parâmetro.

Retornos

Um ConstructorInfo objeto que representa o construtor que corresponde aos requisitos especificados, se encontrado; caso contrário, null.

Implementações

Atributos

Exceções

types é null.

- ou -

Um dos elementos é typesnull.

types é multidimensional.

- ou -

modifiers é multidimensional.

- ou -

types e modifiers não têm o mesmo comprimento.

Exemplos

O exemplo a seguir obtém o tipo de MyClass, obtém o ConstructorInfo objeto e exibe a assinatura do construtor.

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

Comentários

Se uma correspondência exata não existir, tentará binder coagir os tipos de parâmetro especificados na types matriz para selecionar uma correspondência. Se não binder for possível selecionar uma correspondência, será null retornado.

Os seguintes BindingFlags sinalizadores de filtro podem ser usados para definir quais construtores incluir na pesquisa:

  • Você deve especificar ou BindingFlags.Instance ou BindingFlags.Static para obter um retorno.

  • Especifique BindingFlags.Public para incluir construtores públicos na pesquisa.

  • Especifique BindingFlags.NonPublic para incluir construtores não públicos (ou seja, construtores privados, internos e protegidos) na pesquisa.

Consulte System.Reflection.BindingFlags para obter mais informações.

Para obter o inicializador de classe (construtor estático) usando essa sobrecarga de método, você deve especificar BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic no Visual Basic). Você também pode obter o inicializador de classe usando a TypeInitializer propriedade.

Observação

Você não pode omitir parâmetros ao procurar construtores e métodos. Você só pode omitir parâmetros ao invocar.

Se o atual Type representar um tipo genérico construído, este método retorna o ConstructorInfo com os parâmetros de tipo substituídos pelos argumentos de tipo apropriados. Se a corrente Type representar um parâmetro de tipo na definição de um tipo genérico ou método genérico, esse método sempre retornará null.

Confira também

Aplica-se a

GetConstructor(BindingFlags, Type[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Pesquisa um construtor cujos parâmetros correspondem aos tipos de argumento especificados, usando as restrições de associação especificadas.

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

Parâmetros

bindingAttr
BindingFlags

Uma combinação bit a bit dos valores de enumeração que especificam como a pesquisa é conduzida. -ou- Padrão para retornar null.

types
Type[]

Uma matriz de objetos Type que representam o número, a ordem e o tipo dos parâmetros para o construtor obter. -ou- Uma matriz vazia do tipo Type (ou seja, tipos Type[] = Array.Empty{Type}()) para obter um construtor que não usa parâmetros. -ou- EmptyTypes.

Retornos

Um ConstructorInfo objeto que representa o construtor que corresponde aos requisitos especificados, se encontrado; caso contrário, null.

Atributos

Aplica-se a

GetConstructor(Type[])

Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs
Origem:
Type.cs

Pesquisa um construtor de instância pública cujos parâmetros correspondem aos tipos na matriz especificada.

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

Parâmetros

types
Type[]

Uma matriz de Type objetos que representa o número, a ordem e o tipo dos parâmetros para o construtor desejado.

- ou -

Uma matriz vazia de Type objetos, para obter um construtor que não usa parâmetros. Essa matriz vazia é fornecida pelo static campo EmptyTypes.

Retornos

Um objeto que representa o construtor de instância pública cujos parâmetros correspondem aos tipos na matriz de tipo de parâmetro, se encontrado; caso contrário, null.

Implementações

Atributos

Exceções

types é null.

- ou -

Um dos elementos é typesnull.

types é multidimensional.

Exemplos

O exemplo a seguir obtém o tipo de MyClass, obtém o ConstructorInfo objeto e exibe a assinatura do construtor.

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

Comentários

Essa sobrecarga de método procura construtores de instância pública e não pode ser usada para obter um inicializador de classe (construtor estático). Para obter um inicializador de classe, use uma sobrecarga que usa BindingFlagse especifique | BindingFlags.NonPublicBindingFlags.Static(BindingFlags.StaticOrBindingFlags.NonPublic no Visual Basic). Você também pode obter o inicializador de classe usando a TypeInitializer propriedade.

Se o construtor solicitado não for público, esse método retornará null.

Observação

Você não pode omitir parâmetros ao procurar construtores e métodos. Você só pode omitir parâmetros ao invocar.

Se o atual Type representar um tipo genérico construído, este método retorna o ConstructorInfo com os parâmetros de tipo substituídos pelos argumentos de tipo apropriados. Se a corrente Type representar um parâmetro de tipo na definição de um tipo genérico ou método genérico, esse método sempre retornará null.

Confira também

Aplica-se a