Type.GetConstructor Método

Definición

Obtiene un constructor específico del objeto Type actual.

Sobrecargas

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

Busca un constructor cuyos parámetros coincidan con los modificadores y tipos de argumento especificados, mediante las restricciones de enlace indicadas y la convención de llamadas también especificada.

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

Busca un constructor cuyos parámetros coincidan con los tipos y modificadores de argumento especificados, mediante las restricciones de enlace también especificadas.

GetConstructor(BindingFlags, Type[])

Busca un constructor cuyos parámetros coincidan con los tipos de argumento especificados, utilizando las restricciones de enlace especificadas.

GetConstructor(Type[])

Busca un constructor de instancia público cuyos parámetros coincidan con los tipos de la matriz especificada.

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

Busca un constructor cuyos parámetros coincidan con los modificadores y tipos de argumento especificados, mediante las restricciones de enlace indicadas y la convención de llamadas también 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

Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda.

o bien

Default para devolver null.

binder
Binder

Objeto que define un conjunto de propiedades y permite realizar operaciones de enlace, que pueden incluir la selección de un método sobrecargado, la coerción de tipos de argumentos y la invocación de un miembro mediante reflexión.

o bien

Referencia nula (Nothing en Visual Basic) para usar la propiedad DefaultBinder.

callConvention
CallingConventions

Objeto que especifica el conjunto de reglas que se va a usar en cuanto al orden y al diseño de los argumentos, la forma de pasar el valor devuelto, los registros que se usan para los argumentos y la pila que se limpia.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que el constructor debe obtener.

o bien

Matriz vacía del tipo Type (es decir, Type[] types = new Type[0]) para obtener un constructor que no requiera parámetros.

modifiers
ParameterModifier[]

Matriz de objetos ParameterModifier que representan los atributos asociados al elemento correspondiente de la matriz types. El enlazador predeterminado no procesa este parámetro.

Devoluciones

Objeto que representa el constructor que cumple los requisitos especificados, si se encuentra; en caso contrario, es null.

Implementaciones

Atributos

Excepciones

types es null.

o bien

Uno de los elementos de types es null.

types es multidimensional.

o bien

modifiers es multidimensional.

o bien

types y modifiers no tienen la misma longitud.

Ejemplos

En el ejemplo siguiente se obtiene el tipo de MyClass, se obtiene el ConstructorInfo objeto y se muestra la firma del constructor.

using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyClass1
{
public:
   MyClass1( int i ){}

};

int main()
{
   try
   {
      Type^ myType = MyClass1::typeid;
      array<Type^>^types = gcnew array<Type^>(1);
      types[ 0 ] = int::typeid;
      
      // Get the public instance constructor that takes an integer parameter.
      ConstructorInfo^ constructorInfoObj = myType->GetConstructor( static_cast<BindingFlags>(BindingFlags::Instance | BindingFlags::Public), nullptr, CallingConventions::HasThis, types, nullptr );
      if ( constructorInfoObj != nullptr )
      {
         Console::WriteLine( "The constructor of MyClass1 that is a public instance method and takes an integer as a parameter is: " );
         Console::WriteLine( constructorInfoObj );
      }
      else
      {
         Console::WriteLine( "The constructor of MyClass1 that is a public instance method and takes an integer as a parameter is not available." );
      }
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine( "ArgumentNullException: {0}", e->Message );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( "ArgumentException: {0}", e->Message );
   }
   catch ( SecurityException^ e ) 
   {
      Console::WriteLine( "SecurityException: {0}", e->Message );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception: {0}", e->Message );
   }
}
using System;
using System.Reflection;
using System.Security;

public class MyClass3
{
    public MyClass3(int i) { }
    public static void Main()
    {
        try
        {
            Type myType = typeof(MyClass3);
            Type[] types = new Type[1];
            types[0] = typeof(int);
            // Get the public instance constructor that takes an integer parameter.
            ConstructorInfo constructorInfoObj = myType.GetConstructor(
                BindingFlags.Instance | BindingFlags.Public, null,
                CallingConventions.HasThis, types, null);
            if (constructorInfoObj != null)
            {
                Console.WriteLine("The constructor of MyClass3 that is a public " +
                    "instance method and takes an integer as a parameter is: ");
                Console.WriteLine(constructorInfoObj.ToString());
            }
            else
            {
                Console.WriteLine("The constructor of MyClass3 that is a public instance " +
                    "method and takes an integer as a parameter is not available.");
            }
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: " + e.Message);
        }
        catch (ArgumentException e)
        {
            Console.WriteLine("ArgumentException: " + e.Message);
        }
        catch (SecurityException e)
        {
            Console.WriteLine("SecurityException: " + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }
}
open System
open System.Reflection
open System.Security

type MyClass1(i: int) = class end

try
    let myType = typeof<MyClass1>
    let types = [| typeof<int> |]
    // Get the public instance constructor that takes an integer parameter.
    let constructorInfoObj = myType.GetConstructor(BindingFlags.Instance ||| BindingFlags.Public, null, CallingConventions.HasThis, types, null)
    if constructorInfoObj <> null then
        printfn "The constructor of MyClass1 that is a public instance method and takes an integer as a parameter is: \n{constructorInfoObj}"
    else
        printfn "The constructor of MyClass1 that is a public instance method and takes an integer as a parameter is not available."
with
| :? ArgumentNullException as e ->
    printfn $"ArgumentNullException: {e.Message}"
| :? ArgumentException as e ->
    printfn $"ArgumentException: {e.Message}"
| :? SecurityException as e ->
    printfn $"SecurityException: {e.Message}"
| e ->
    printfn $"Exception: {e.Message}"
Public Class MyClass1
    Public Sub New(ByVal i As Integer)
    End Sub
    Public Shared Sub Main()
        Try
            Dim myType As Type = GetType(MyClass1)
            Dim types(0) As Type
            types(0) = GetType(Integer)
            ' Get the public instance constructor that takes an integer parameter.
            Dim constructorInfoObj As ConstructorInfo = _
                        myType.GetConstructor(BindingFlags.Instance Or _
                        BindingFlags.Public, Nothing, _
                        CallingConventions.HasThis, types, Nothing)
            If Not (constructorInfoObj Is Nothing) Then
                Console.WriteLine("The constructor of MyClass1 that " + _
                                  "is a public instance method and takes an " + _
                                  "integer as a parameter is: ")
                Console.WriteLine(constructorInfoObj.ToString())
            Else
                Console.WriteLine("The constructor MyClass1 that " + _
                                  "is a public instance method and takes an " + _
                                  "integer as a parameter is not available.")
            End If
        Catch e As ArgumentNullException
            Console.WriteLine("ArgumentNullException: " + e.Message)
        Catch e As ArgumentException
            Console.WriteLine("ArgumentException: " + e.Message)
        Catch e As SecurityException
            Console.WriteLine("SecurityException: " + e.Message)
        Catch e As Exception
            Console.WriteLine("Exception: " + e.Message)
        End Try
    End Sub
End Class

Comentarios

Aunque el enlazador predeterminado no procesa ParameterModifier (el modifiers parámetro ), puede usar la clase abstracta System.Reflection.Binder para escribir un enlazador personalizado que procesa modifiers. ParameterModifier solo se usa al llamar a través de la interoperabilidad COM y solo se controlan los parámetros que se pasan por referencia.

Si no existe una coincidencia exacta, binder intentará convertir los tipos de parámetro especificados en la types matriz para seleccionar una coincidencia. Si no binder puede seleccionar una coincidencia, null se devuelve .

Se pueden usar las marcas de filtro siguientes BindingFlags para definir qué constructores se van a incluir en la búsqueda:

  • Debe especificar o BindingFlags.InstanceBindingFlags.Static para obtener una devolución.

  • Especifique BindingFlags.Public para incluir constructores públicos en la búsqueda.

  • Especifique BindingFlags.NonPublic para incluir constructores no públicos (es decir, constructores privados, internos y protegidos) en la búsqueda.

Vea System.Reflection.BindingFlags para obtener más información.

Para obtener el inicializador de clase (constructor estático) mediante este método, debe especificar BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic en Visual Basic). También puede obtener el inicializador de clase mediante la TypeInitializer propiedad .

En la tabla siguiente se muestra qué miembros de una clase base devuelven los Get métodos al reflejar en un tipo.

Tipo de miembro Estático No estático
Constructor No No
Campo No Sí. Un campo siempre se oculta por nombre y firma.
evento No es aplicable La regla del sistema de tipos común es que la herencia es la misma que la de los métodos que implementan la propiedad . La reflexión trata las propiedades como hide-by-name-and-signature. Consulte la nota 2 a continuación.
Método No Sí. Un método (tanto virtual como no virtual) puede ser hide-by-name u hide-by-name-and-signature.
Tipo anidado No No
Propiedad. No es aplicable La regla del sistema de tipos común es que la herencia es la misma que la de los métodos que implementan la propiedad . La reflexión trata las propiedades como hide-by-name-and-signature. Consulte la nota 2 a continuación.
  1. Hide-by-name-and-signature tiene en cuenta todas las partes de la firma, incluidos modificadores personalizados, tipos de valor devuelto, tipos de parámetros, sentinels y convenciones de llamada no administradas. Se trata de una comparación binaria.

  2. Para la reflexión, las propiedades y los eventos son hide-by-name-and-signature. Si tiene una propiedad con un descriptor de acceso get y un set en la clase base, pero la clase derivada solo tiene un descriptor de acceso get, la propiedad de clase derivada oculta la propiedad de clase base y no podrá tener acceso al establecedor en la clase base.

  3. Los atributos personalizados no forman parte del sistema de tipos común.

Nota

No se pueden omitir parámetros al buscar constructores y métodos. Solo se pueden omitir los parámetros al invocar.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con ConstructorInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados. Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método siempre devuelve null.

Consulte también

Se aplica a

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

Busca un constructor cuyos parámetros coincidan con los tipos y modificadores de argumento especificados, mediante las restricciones de enlace también 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

Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda.

o bien

Default para devolver null.

binder
Binder

Objeto que define un conjunto de propiedades y permite realizar operaciones de enlace, que pueden incluir la selección de un método sobrecargado, la coerción de tipos de argumentos y la invocación de un miembro mediante reflexión.

o bien

Referencia nula (Nothing en Visual Basic) para usar la propiedad DefaultBinder.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que el constructor debe obtener.

o bien

Matriz vacía del tipo Type (es decir, Type[] types = new Type[0]) para obtener un constructor que no requiera parámetros.

o bien

EmptyTypes.

modifiers
ParameterModifier[]

Matriz de objetos ParameterModifier que representan los atributos asociados al elemento correspondiente de la matriz de tipo de parámetro. El enlazador predeterminado no procesa este parámetro.

Devoluciones

Objeto ConstructorInfo que representa el constructor que cumple los requisitos especificados, si se encuentra; en caso contrario, es null.

Implementaciones

Atributos

Excepciones

types es null.

o bien

Uno de los elementos de types es null.

types es multidimensional.

o bien

modifiers es multidimensional.

o bien

types y modifiers no tienen la misma longitud.

Ejemplos

En el ejemplo siguiente se obtiene el tipo de MyClass, se obtiene el ConstructorInfo objeto y se muestra la firma del constructor.

using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyClass1
{
public:
   MyClass1( int i ){}

};

int main()
{
   try
   {
      Type^ myType = MyClass1::typeid;
      array<Type^>^types = gcnew array<Type^>(1);
      types[ 0 ] = int::typeid;
      
      // Get the constructor that is public and takes an integer parameter.
      ConstructorInfo^ constructorInfoObj = myType->GetConstructor( static_cast<BindingFlags>(BindingFlags::Instance | BindingFlags::Public), nullptr, types, nullptr );
      if ( constructorInfoObj != nullptr )
      {
         Console::WriteLine( "The constructor of MyClass1 that is public and takes an integer as a parameter is:" );
         Console::WriteLine( constructorInfoObj );
      }
      else
      {
         Console::WriteLine( "The constructor of the MyClass1 that is public and takes an integer as a parameter is not available." );
      }
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine( "ArgumentNullException: {0}", e->Message );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( "ArgumentException: {0}", e->Message );
   }
   catch ( SecurityException^ e ) 
   {
      Console::WriteLine( "SecurityException: {0}", e->Message );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception: {0}", e->Message );
   }
}
using System;
using System.Reflection;
using System.Security;

public class MyClass2
{
    public MyClass2(int i) { }
    public static void Main()
    {
        try
        {
            Type myType = typeof(MyClass2);
            Type[] types = new Type[1];
            types[0] = typeof(int);
            // Get the constructor that is public and takes an integer parameter.
            ConstructorInfo constructorInfoObj = myType.GetConstructor(
                BindingFlags.Instance | BindingFlags.Public, null, types, null);
            if (constructorInfoObj != null)
            {
                Console.WriteLine("The constructor of MyClass2 that is public " +
                    "and takes an integer as a parameter is:");
                Console.WriteLine(constructorInfoObj.ToString());
            }
            else
            {
                Console.WriteLine("The constructor of the MyClass2 that is public " +
                    "and takes an integer as a parameter is not available.");
            }
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: " + e.Message);
        }
        catch (ArgumentException e)
        {
            Console.WriteLine("ArgumentException: " + e.Message);
        }
        catch (SecurityException e)
        {
            Console.WriteLine("SecurityException: " + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }
}
open System
open System.Reflection
open System.Security

type MyClass1(i: int) = class end

try
    let myType = typeof<MyClass1>
    let types = [| typeof<int> |]
    // Get the constructor that is public and takes an integer parameter.
    let constructorInfoObj = myType.GetConstructor(BindingFlags.Instance ||| BindingFlags.Public, null, types, null)
    if constructorInfoObj <> null then
        printfn "The constructor of MyClass1 that is public and takes an integer as a parameter is:\n{constructorInfoObj}"
    else
        printfn "The constructor of the MyClass1 that is public and takes an integer as a parameter is not available."
with
| :? ArgumentNullException as e ->
    printfn $"ArgumentNullException: {e.Message}"
| :? ArgumentException as e ->
    printfn $"ArgumentException: {e.Message}"
| :? SecurityException as e ->
    printfn $"SecurityException: {e.Message}"
| e ->
    printfn $"Exception: {e.Message}"
Imports System.Reflection
Imports System.Security


Public Class MyClass1
    Public Sub New(ByVal i As Integer)
    End Sub

    Public Shared Sub Main()
        Try
            Dim myType As Type = GetType(MyClass1)
            Dim types(0) As Type
            types(0) = GetType(Integer)
            ' Get the constructor that is public and takes an integer parameter.
            Dim constructorInfoObj As ConstructorInfo = _
                     myType.GetConstructor(BindingFlags.Instance Or _
                     BindingFlags.Public, Nothing, types, Nothing)
            If Not (constructorInfoObj Is Nothing) Then
                Console.WriteLine("The constructor of MyClass1 that is " + _
                               "public and takes an integer as a parameter is ")
                Console.WriteLine(constructorInfoObj.ToString())
            Else
                Console.WriteLine("The constructor of MyClass1 that is " + _
                  "public and takes an integer as a parameter is not available.")
            End If
        Catch e As ArgumentNullException
            Console.WriteLine("ArgumentNullException: " + e.Message)
        Catch e As ArgumentException
            Console.WriteLine("ArgumentException: " + e.Message)
        Catch e As SecurityException
            Console.WriteLine("SecurityException: " + e.Message)
        Catch e As Exception
            Console.WriteLine("Exception: " + e.Message)
        End Try
    End Sub
End Class

Comentarios

Si no existe una coincidencia exacta, binder intentará convertir los tipos de parámetro especificados en la types matriz para seleccionar una coincidencia. Si no binder puede seleccionar una coincidencia, null se devuelve .

Se pueden usar las marcas de filtro siguientes BindingFlags para definir qué constructores se van a incluir en la búsqueda:

  • Debe especificar o BindingFlags.InstanceBindingFlags.Static para obtener una devolución.

  • Especifique BindingFlags.Public para incluir constructores públicos en la búsqueda.

  • Especifique BindingFlags.NonPublic para incluir constructores no públicos (es decir, constructores privados, internos y protegidos) en la búsqueda.

Vea System.Reflection.BindingFlags para obtener más información.

Para obtener el inicializador de clase (constructor estático) mediante esta sobrecarga de método, debe especificar BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic en Visual Basic). También puede obtener el inicializador de clase mediante la TypeInitializer propiedad .

Nota

No se pueden omitir parámetros al buscar constructores y métodos. Solo se pueden omitir los parámetros al invocar.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con ConstructorInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados. Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método siempre devuelve null.

Consulte también

Se aplica a

GetConstructor(BindingFlags, Type[])

Busca un constructor cuyos parámetros coincidan con los tipos de argumento especificados, utilizando las restricciones de enlace 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

Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda. -o bien- Valor predeterminado para devolver null.

types
Type[]

Matriz de objetos Type que representan el número, el orden y el tipo de los parámetros que se van a obtener para el constructor. -o bien- Una matriz vacía del tipo Type (es decir, Type[] types = Array.Empty{Type}()) para obtener un constructor que no toma parámetros. -o bien- EmptyTypes.

Devoluciones

Objeto ConstructorInfo que representa el constructor que cumple los requisitos especificados, si se encuentra; en caso contrario, es null.

Se aplica a

GetConstructor(Type[])

Busca un constructor de instancia público cuyos parámetros coincidan con los tipos de la 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[]

Matriz de objetos Type que representa el número, el orden y el tipo de los parámetros del constructor deseado.

o bien

Matriz vacía de objetos Type, para obtener un constructor que no requiera parámetros. El campo staticEmptyTypes proporciona dicha matriz vacía.

Devoluciones

Objeto que representa el constructor de instancia público cuyos parámetros coinciden con los tipos de la matriz de tipos de parámetro, si se encuentra; de lo contrario, es null.

Implementaciones

Atributos

Excepciones

types es null.

o bien

Uno de los elementos de types es null.

types es multidimensional.

Ejemplos

En el ejemplo siguiente se obtiene el tipo de MyClass, se obtiene el ConstructorInfo objeto y se muestra la firma del constructor.

using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyClass1
{
public:
   MyClass1(){}

   MyClass1( int i ){}

};

int main()
{
   try
   {
      Type^ myType = MyClass1::typeid;
      array<Type^>^types = gcnew array<Type^>(1);
      types[ 0 ] = int::typeid;
      
      // Get the constructor that takes an integer as a parameter.
      ConstructorInfo^ constructorInfoObj = myType->GetConstructor( types );
      if ( constructorInfoObj != nullptr )
      {
         Console::WriteLine( "The constructor of MyClass1 that takes an integer as a parameter is: " );
         Console::WriteLine( constructorInfoObj );
      }
      else
      {
         Console::WriteLine( "The constructor of MyClass1 that takes an integer as a parameter is not available." );
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception caught." );
      Console::WriteLine( "Source: {0}", e->Source );
      Console::WriteLine( "Message: {0}", e->Message );
   }
}
using System;
using System.Reflection;

public class MyClass1
{
    public MyClass1() { }
    public MyClass1(int i) { }

    public static void Main()
    {
        try
        {
            Type myType = typeof(MyClass1);
            Type[] types = new Type[1];
            types[0] = typeof(int);
            // Get the constructor that takes an integer as a parameter.
            ConstructorInfo constructorInfoObj = myType.GetConstructor(types);
            if (constructorInfoObj != null)
            {
                Console.WriteLine("The constructor of MyClass1 that takes an " +
                    "integer as a parameter is: ");
                Console.WriteLine(constructorInfoObj.ToString());
            }
            else
            {
                Console.WriteLine("The constructor of MyClass1 that takes an integer " +
                    "as a parameter is not available.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception caught.");
            Console.WriteLine("Source: " + e.Source);
            Console.WriteLine("Message: " + e.Message);
        }
    }
}
type MyClass1() =
    new (i: int) = MyClass1()

try
    let myType = typeof<MyClass1>
    let types = [| typeof<int> |]
    // Get the constructor that takes an integer as a parameter.
    let constructorInfoObj = myType.GetConstructor types
    if constructorInfoObj <> null then
        printfn "The constructor of MyClass1 that takes an integer as a parameter is: \n{constructorInfoObj}"
    else
        printfn "The constructor of MyClass1 that takes an integer as a parameter is not available."
with e ->
    printfn "Exception caught."
    printfn $"Source: {e.Source}"
    printfn $"Message: {e.Message}"
Imports System.Reflection
Imports System.Security

Public Class MyClass1

    Public Sub New()
    End Sub

    Public Sub New(ByVal i As Integer)
    End Sub

    Public Shared Sub Main()
        Try
            Dim myType As Type = GetType(MyClass1)
            Dim types(0) As Type
            types(0) = GetType(Int32)
            ' Get the constructor that takes an integer as a parameter.
            Dim constructorInfoObj As ConstructorInfo = myType.GetConstructor(types)
            If Not (constructorInfoObj Is Nothing) Then
                Console.WriteLine("The constructor of MyClass that takes an integer as a parameter is: ")
                Console.WriteLine(constructorInfoObj.ToString())
            Else
                Console.WriteLine("The constructor of MyClass that takes no " + "parameters is not available.")
            End If

        Catch e As Exception
            Console.WriteLine("Exception caught.")
            Console.WriteLine(("Source: " + e.Source))
            Console.WriteLine(("Message: " + e.Message))
        End Try
    End Sub
End Class

Comentarios

Esta sobrecarga de método busca constructores de instancias públicas y no se puede usar para obtener un inicializador de clase (constructor estático). Para obtener un inicializador de clase, use una sobrecarga que tome BindingFlagsy especifique BindingFlags.StaticBindingFlags.NonPublic | (BindingFlags.StaticOrBindingFlags.NonPublic en Visual Basic). También puede obtener el inicializador de clase mediante la TypeInitializer propiedad .

Si el constructor solicitado no es público, este método devuelve null.

Nota

No se pueden omitir parámetros al buscar constructores y métodos. Solo se pueden omitir los parámetros al invocar.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con ConstructorInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados. Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método siempre devuelve null.

Consulte también

Se aplica a