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(Type[])

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

GetConstructor(BindingFlags, Type[])

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

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

ConstructorInfo

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 objeto y se muestra la firma del ConstructorInfo 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 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

Comentarios

Aunque el enlazador predeterminado no procesa (el parámetro ), puede usar la clase abstracta para escribir un ParameterModifier modifiers System.Reflection.Binder enlazador personalizado que procese 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, intentará convertir los tipos de parámetro especificados en la matriz para binder types seleccionar una coincidencia. Si no binder puede seleccionar una coincidencia, se devuelve null .

Las siguientes BindingFlags marcas de filtro se pueden usar para definir los constructores que se incluirán en la búsqueda:

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

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

  • Especifique para incluir constructores no públicos (es decir, constructores privados, internos y BindingFlags.NonPublic 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 ( en BindingFlags.Static Or BindingFlags.NonPublic 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 métodos Get 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 común del sistema de tipos 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. Vea la nota 2 a continuación.
Método No Sí. Un método (virtual y no virtual) puede ocultarse por nombre u ocultar por nombre y firma.
Tipo anidado No No
Propiedad. No es aplicable La regla común del sistema de tipos 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. Vea la nota 2 a continuación.
  1. Ocultar por nombre y firma tiene en cuenta todas las partes de la firma, incluidos modificadores personalizados, tipos de valor devuelto, tipos de parámetros, centinelas y convenciones de llamada no administradas. Se trata de una comparación binaria.

  2. Para la reflexión, las propiedades y los eventos se ocultan por nombre y firma. Si tiene una propiedad con un accessor get y set en la clase base, pero la clase derivada solo tiene un accessor get, la propiedad de clase derivada oculta la propiedad de clase base y no podrá acceder al establecedor en la clase base.

  3. Los atributos personalizados no forman parte del sistema de tipos comunes.

Nota

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

Si el objeto actual representa un tipo genérico construido, este método devuelve con los parámetros Type ConstructorInfo de tipo reemplazados por los argumentos de tipo adecuados. Si el objeto actual representa un parámetro de tipo en la definición de un tipo genérico o un método Type 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

ConstructorInfo

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 objeto y se muestra la firma del ConstructorInfo 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 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

Comentarios

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

Las siguientes BindingFlags marcas de filtro se pueden usar para definir los constructores que se incluirán en la búsqueda:

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

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

  • Especifique para incluir constructores no públicos (es decir, constructores privados, internos y BindingFlags.NonPublic 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 ( en BindingFlags.Static Or BindingFlags.NonPublic 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 puede omitir parámetros al invocar.

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

Consulte también

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

ConstructorInfo

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 objeto y se muestra la firma del ConstructorInfo 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;
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

Comentarios

Esta sobrecarga de método busca constructores de instancia pública 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 BindingFlags y especifique | ( en BindingFlags.Static BindingFlags.NonPublic BindingFlags.Static Or BindingFlags.NonPublic 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 puede omitir parámetros al invocar.

Si el objeto actual representa un tipo genérico construido, este método devuelve con los parámetros de tipo Type ConstructorInfo reemplazados por los argumentos de tipo adecuados. Si el objeto actual representa un parámetro de tipo en la definición de un tipo genérico o un método Type 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 representa el número, el orden y el tipo de los parámetros que el constructor debe obtener. -o bien- Una matriz vacía del tipo Type (es decir, Type[] types = Array.Empty{Type}()) para obtener un constructor que no toma ningún parámetro. -o bien- EmptyTypes .

Devoluciones

ConstructorInfo

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

Se aplica a