Type.GetConstructor Método
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Obtém um construtor específico do Type atual.
Sobrecargas
GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) |
Pesquisa por 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 o construtor cujos parâmetros correspondem aos tipos de argumento e modificadores 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, Type[]) |
Pesquisa um Construtor cujos parâmetros correspondem aos tipos de argumento especificados, usando as restrições de associação especificadas. |
GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
Pesquisa por 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);
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
Parâmetros
- bindingAttr
- BindingFlags
Uma combinação bit a bit dos valores de enumeração que especificam como a pesquisa é realizada.
- ou -
Default para retornar
null
.
- binder
- Binder
Um objeto que define um conjunto de propriedades e habilita a associação, que pode envolver seleção de um método sobrecarregado, coerção de tipos de argumento e 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 ao layout dos argumentos, a maneira como o valor retornado é passado, a quais registros são usados para argumentos e à forma que a pilha é limpa.
- types
- Type[]
Uma matriz de objetos Type que representam o número, a ordem e o tipo de parâmetros para o construtor obter.
- ou - Uma matriz vazia do tipo Type (ou seja, Type[] types = new Type[0]) para obter um construtor sem parâmetros.
- modifiers
- ParameterModifier[]
Uma matriz de objetos ParameterModifier que representam os atributos associados ao elemento correspondente na matriz types
. O associador padrão não processa este 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
é multidimensional.
ou -
modifiers
é multidimensional.ou -
types
emodifiers
não têm o mesmo tamanho.
Exemplos
O exemplo a seguir obtém o tipo de MyClass
, obtém o ConstructorInfo objeto e exibe a assinatura do construtor.
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 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 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 MyClass1 that is a public " +
"instance method and takes an integer as a parameter is: ");
Console.WriteLine(constructorInfoObj.ToString());
}
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: " + 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);
}
}
}
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 parâmetro modifiers
), é possível usar a classe abstrata System.Reflection.Binder para gravar um associador personalizado que processa modifiers
. ParameterModifier
é usado apenas ao chamar por meio de interoperabilidade COM e apenas parâmetros que são passados por referência são manipulados.
Se uma correspondência exata não existir, o binder
tentará forçar os tipos de parâmetro especificados na matriz types
para selecionar uma correspondência. Se o binder
não for capaz de selecionar uma correspondência, null
será retornado.
Os seguintes sinalizadores de filtro BindingFlags podem ser usados para definir quais construtores devem ser incluídos na pesquisa:
Você deve especificar
BindingFlags.Instance
ouBindingFlags.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 particulares, 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.Static Or
BindingFlags.NonPublic em Visual Basic). Também é possível obter o inicializador da classe usando-se a propriedade TypeInitializer.
A tabela a seguir mostra quais membros de uma classe base são retornados pelos métodos Get
durante a reflexão em um tipo.
Tipo do membro | Estático | Não estático |
---|---|---|
Construtor | Não | Não |
Campo | Não | Sim. Um campo permanece sempre oculto por nome e assinatura. |
Evento | Não aplicável | A regra de sistema do tipo comum é que a herança é a mesma dos métodos que implementam a propriedade. Reflexão trata propriedades como ocultas por nome e assinatura. Consulte a observação 2 abaixo. |
Método | Não | Sim. Um método (virtual e não virtual) pode permanecer oculto por nome ou por nome e assinatura. |
Tipo aninhado | Não | Não |
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. Reflexão trata propriedades como ocultas por nome e assinatura. Consulte a observação 2 abaixo. |
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. Esta é uma comparação binária.
Para reflexão, propriedades e eventos permanecem ocultos por nome e assinatura. Se você tiver uma propriedade com um acessador get e set na classe base, mas a classe derivada tiver apenas um acessador get, a propriedade de classe derivada ocultará a propriedade da classe base e você não poderá acessar o setter na classe base.
Atributos personalizados não fazem parte do sistema de tipo comum.
Observação
Não é possível omitir parâmetros durante a pesquisa de construtores e métodos. Só é possível omitir parâmetros durante a invocação.
Caso o Type atual represente 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 Current Type representar um parâmetro de tipo na definição de um tipo genérico ou um método genérico, esse método sempre retornará null
.
Confira também
- ConstructorInfo
- BindingFlags
- Binder
- DefaultBinder
- CallingConventions
- ParameterModifier
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()
Aplica-se a
GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[])
Pesquisa o 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);
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
Parâmetros
- bindingAttr
- BindingFlags
Uma combinação bit a bit dos valores de enumeração que especificam como a pesquisa é realizada.
- ou -
Default para retornar
null
.
- binder
- Binder
Um objeto que define um conjunto de propriedades e habilita a associação, que pode envolver seleção de um método sobrecarregado, coerção de tipos de argumento e 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 objetos Type que representam o número, a ordem e o tipo de parâmetros para o construtor obter.
ou - Uma matriz vazia do tipo Type (ou seja, Type[] types = new Type[0]) para obter um construtor sem parâmetros.
ou - EmptyTypes.
- modifiers
- ParameterModifier[]
Uma matriz de objetos ParameterModifier que representam os atributos associados ao elemento correspondente na matriz de tipo de parâmetro. O associador padrão não processa este parâmetro.
Retornos
Um objeto ConstructorInfo que representa o construtor que corresponde aos requisitos especificados, se encontrados, caso contrário, null
.
Implementações
- Atributos
Exceções
types
é multidimensional.
ou -
modifiers
é multidimensional.ou -
types
emodifiers
não têm o mesmo tamanho.
Exemplos
O exemplo a seguir obtém o tipo de MyClass
, obtém o ConstructorInfo objeto e exibe a assinatura do construtor.
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 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 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 MyClass1 that is public " +
"and takes an integer as a parameter is:");
Console.WriteLine(constructorInfoObj.ToString());
}
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: " + 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);
}
}
}
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, o binder
tentará forçar os tipos de parâmetro especificados na matriz types
para selecionar uma correspondência. Se o binder
não for capaz de selecionar uma correspondência, null
será retornado.
Os seguintes sinalizadores de filtro BindingFlags podem ser usados para definir quais construtores devem ser incluídos na pesquisa:
Você deve especificar
BindingFlags.Instance
ouBindingFlags.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 particulares, 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.Static Or
BindingFlags.NonPublic em Visual Basic). Também é possível obter o inicializador da classe usando-se a propriedade TypeInitializer.
Observação
Não é possível omitir parâmetros durante a pesquisa de construtores e métodos. Só é possível omitir parâmetros durante a invocação.
Caso o Type atual represente 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 Current Type representar um parâmetro de tipo na definição de um tipo genérico ou um método genérico, esse método sempre retornará null
.
Confira também
- ConstructorInfo
- BindingFlags
- Binder
- DefaultBinder
- ParameterModifier
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()
Aplica-se a
GetConstructor(Type[])
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);
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
Parâmetros
- types
- Type[]
Uma matriz de objetos Type que representam o número, a ordem e o tipo de parâmetros para o construtor desejado.
- ou -
Uma matriz vazia de objetos Type, para obter um construtor que não aceita parâmetros. Tal matriz vazia é fornecida pelo campo
static
de EmptyTypes.
Retornos
Um objeto que representa o construtor de instância pública cujos parâmetros correspondem aos tipos na matriz de tipos de parâmetro, se encontrado; caso contrário, null
.
Implementações
- Atributos
Exceções
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 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;
using System.Security;
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);
}
}
}
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 aceite BindingFlags e especifique BindingFlags.Static | BindingFlags.NonPublic ( BindingFlags.Static Or
BindingFlags.NonPublic em Visual Basic). Também é possível obter o inicializador da classe usando-se a propriedade TypeInitializer.
Se o construtor solicitado for não público, esse método retornará null
.
Observação
Não é possível omitir parâmetros durante a pesquisa de construtores e métodos. Só é possível omitir parâmetros durante a invocação.
Caso o Type atual represente 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 Current Type representar um parâmetro de tipo na definição de um tipo genérico ou um método genérico, esse método sempre retornará null
.
Confira também
- ConstructorInfo
- DefaultBinder
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()
Aplica-se a
GetConstructor(BindingFlags, Type[])
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);
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
Parâmetros
- bindingAttr
- BindingFlags
Uma combinação bit a bit dos valores de enumeração que especificam como a pesquisa é realizada.
-ou-padrão para retornar null
.
- types
- Type[]
Uma matriz de objetos de tipo que representa o número, a ordem e o tipo dos parâmetros a serem obtidos pelo construtor. -ou-uma matriz vazia do tipo Type (ou seja, tipo [] Types = array. vazio {Type} ()) para obter um construtor que não usa parâmetros. -ou- EmptyTypes .
Retornos
Um objeto ConstructorInfo que representa o construtor que corresponde aos requisitos especificados, se encontrados, caso contrário, null
.