Type.GetConstructor Metodo

Definizione

Ottiene un costruttore specifico dell'oggetto Type corrente.

Overload

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

Cerca il costruttore i cui parametri corrispondono ai tipi di argomenti e ai modificatori specificati, usando i vincoli di associazione e la convenzione di chiamata specificati.

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

Cerca un costruttore i cui parametri corrispondono ai tipi e ai modificatori dell'argomento specificato, usando i vincoli di associazione specificati.

GetConstructor(BindingFlags, Type[])

Cerca un costruttore i cui parametri corrispondono ai tipi di argomento specificati, usando i vincoli di associazione specificati.

GetConstructor(Type[])

Cerca un costruttore di istanza pubblica i cui parametri corrispondono ai tipi nella matrice specificata.

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

Cerca il costruttore i cui parametri corrispondono ai tipi di argomenti e ai modificatori specificati, usando i vincoli di associazione e la convenzione di chiamata specificati.

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

Parametri

bindingAttr
BindingFlags

Combinazione bit per bit di valori di enumerazione che specifica il modo in cui viene eseguita la ricerca.

-oppure-

Default per restituire null.

binder
Binder

Oggetto che definisce una serie di proprietà e permette il binding, che può implicare la scelta di un metodo di overload, la coercizione di tipi di argomento e la chiamata di un membro mediante reflection.

-oppure-

Riferimento Null (Nothing in Visual Basic) per l'uso di DefaultBinder.

callConvention
CallingConventions

Oggetto che specifica il set di regole da usare per l'ordine e il layout degli argomenti, la modalità di passaggio del valore restituito, i Registri di sistema usati per gli argomenti e la pulizia dello stack.

types
Type[]

Matrice di oggetti Type che rappresenta numero, ordine e tipo dei parametri relativi al costruttore da ottenere.

-oppure-

Matrice vuota di tipo Type (ovvero Type[] types = new Type[0]) per ottenere un costruttore che non accetta parametri.

modifiers
ParameterModifier[]

Matrice di oggetti ParameterModifier che rappresentano gli attributi associati all'elemento corrispondente nella matrice types. Questo parametro non viene elaborato dal binder predefinito.

Restituisce

Oggetto che rappresenta il costruttore corrispondente ai requisiti specificati, se è stato trovato; in caso contrario, null.

Implementazioni

Attributi

Eccezioni

types è null.

-oppure-

Uno degli elementi in types è null.

types è multidimensionale.

-oppure-

modifiers è multidimensionale.

-oppure-

types e modifiers non hanno la stessa lunghezza.

Esempio

Nell'esempio seguente viene ottenuto il tipo di MyClass, viene ottenuto l'oggetto ConstructorInfo e viene visualizzata la firma del costruttore.

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

Commenti

Anche se il binder predefinito non elabora ParameterModifier (il parametro ), è possibile usare la classe astratta System.Reflection.Binder per scrivere un binder personalizzato che esegue l'elaborazione modifiersmodifiersdi . ParameterModifier viene usato solo quando si chiama tramite l'interoperabilità COM e vengono gestiti solo i parametri passati per riferimento.

Se non esiste una corrispondenza esatta, binder tenterà di forzare i tipi di parametro specificati nella types matrice per selezionare una corrispondenza. Se non binder è possibile selezionare una corrispondenza, null viene restituito .

È possibile usare i flag di filtro seguenti BindingFlags per definire i costruttori da includere nella ricerca:

  • È necessario specificare BindingFlags.Instance o BindingFlags.Static per ottenere un ritorno.

  • Specificare BindingFlags.Public di includere costruttori pubblici nella ricerca.

  • Specificare BindingFlags.NonPublic di includere costruttori non pubblici (ovvero costruttori privati, interni e protetti) nella ricerca.

Per altre informazioni, vedere System.Reflection.BindingFlags.

Per ottenere l'inizializzatore di classe (costruttore statico) usando questo metodo, è necessario specificare BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic in Visual Basic). È anche possibile ottenere l'inizializzatore di classe usando la TypeInitializer proprietà .

Nella tabella seguente vengono illustrati i membri di una classe base restituiti dai Get metodi quando si riflette su un tipo.

Tipo di membro Static Non statico
Costruttore No No
Campo No Sì. Un campo è sempre hide-by-name-and-signature.
Evento Non applicabile La regola di sistema dei tipi comune è che l'ereditarietà è uguale a quella dei metodi che implementano la proprietà . La reflection considera le proprietà come hide-by-name-and-signature. Vedere la nota 2 di seguito.
Metodo No Sì. Un metodo (sia virtuale che non virtuale) può essere hide-by-name o hide-by-name-and-signature.
Tipo annidato No No
Proprietà Non applicabile La regola di sistema dei tipi comune è che l'ereditarietà è uguale a quella dei metodi che implementano la proprietà . La reflection considera le proprietà come hide-by-name-and-signature. Vedere la nota 2 di seguito.
  1. Hide-by-name-and-signature considera tutte le parti della firma, inclusi modificatori personalizzati, tipi restituiti, tipi di parametro, sentinel e convenzioni di chiamata non gestite. Si tratta di un confronto binario.

  2. Per la reflection, le proprietà e gli eventi sono hide-by-name-and-signature. Se nella classe base è presente una proprietà con una funzione di accesso get e una funzione di accesso set, ma la classe derivata ha solo una funzione di accesso get, la proprietà della classe derivata nasconde la proprietà della classe base e non sarà possibile accedere al setter nella classe base.

  3. Gli attributi personalizzati non fanno parte del sistema di tipi comuni.

Nota

Non è possibile omettere parametri durante la ricerca di costruttori e metodi. È possibile omettere i parametri solo quando si richiama.

Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce con ConstructorInfo i parametri di tipo sostituiti dagli argomenti di tipo appropriati. Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo generico o di un metodo generico, questo metodo restituisce nullsempre .

Vedi anche

Si applica a

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

Cerca un costruttore i cui parametri corrispondono ai tipi e ai modificatori dell'argomento specificato, usando i vincoli di associazione specificati.

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

Parametri

bindingAttr
BindingFlags

Combinazione bit per bit di valori di enumerazione che specifica il modo in cui viene eseguita la ricerca.

-oppure-

Default per restituire null.

binder
Binder

Oggetto che definisce una serie di proprietà e permette il binding, che può implicare la scelta di un metodo di overload, la coercizione di tipi di argomento e la chiamata di un membro mediante reflection.

-oppure-

Riferimento Null (Nothing in Visual Basic) per l'uso di DefaultBinder.

types
Type[]

Matrice di oggetti Type che rappresenta numero, ordine e tipo dei parametri relativi al costruttore da ottenere.

-oppure-

Matrice vuota di tipo Type (ovvero Type[] types = new Type[0]) per ottenere un costruttore che non accetta parametri.

-oppure-

EmptyTypes.

modifiers
ParameterModifier[]

Matrice di oggetti ParameterModifier che rappresentano gli attributi associati all'elemento corrispondente nella matrice del tipo di parametro. Questo parametro non viene elaborato dal binder predefinito.

Restituisce

Oggetto ConstructorInfo che rappresenta il costruttore corrispondente ai requisiti specificati, se presente; in caso contrario, null.

Implementazioni

Attributi

Eccezioni

types è null.

-oppure-

Uno degli elementi in types è null.

types è multidimensionale.

-oppure-

modifiers è multidimensionale.

-oppure-

types e modifiers non hanno la stessa lunghezza.

Esempio

Nell'esempio seguente viene ottenuto il tipo di MyClass, viene ottenuto l'oggetto ConstructorInfo e viene visualizzata la firma del costruttore.

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

Commenti

Se non esiste una corrispondenza esatta, il binder tentativo di coercere i tipi di parametri specificati nella types matrice per selezionare una corrispondenza. Se l'oggetto binder non è in grado di selezionare una corrispondenza, null viene restituito.

I flag di filtro seguenti BindingFlags possono essere usati per definire quali costruttori includere nella ricerca:

  • È necessario specificare BindingFlags.Instance o BindingFlags.Static per ottenere un ritorno.

  • Specificare BindingFlags.Public per includere costruttori pubblici nella ricerca.

  • Specificare BindingFlags.NonPublic per includere costruttori non pubblici ,ovvero costruttori privati, interni e protetti) nella ricerca.

Per altre informazioni, vedere System.Reflection.BindingFlags.

Per ottenere l'inizializzatore di classe (costruttore statico) usando questo overload del metodo, è necessario specificare BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOrBindingFlags.NonPublic in Visual Basic). È anche possibile ottenere l'inizializzatore di classe usando la TypeInitializer proprietà .

Nota

Non è possibile omettere i parametri durante la ricerca di costruttori e metodi. È possibile omettere solo i parametri quando si richiama.

Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce con ConstructorInfo i parametri di tipo sostituiti dagli argomenti di tipo appropriati. Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo generico o di un metodo generico, questo metodo restituisce nullsempre .

Vedi anche

Si applica a

GetConstructor(BindingFlags, Type[])

Cerca un costruttore i cui parametri corrispondono ai tipi di argomenti specificati usando i vincoli di associazione specificati.

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

Parametri

bindingAttr
BindingFlags

Combinazione bit per bit di valori di enumerazione che specifica il modo in cui viene eseguita la ricerca. -o- Impostazione predefinita per restituire null.

types
Type[]

Matrice di oggetti Type che rappresentano il numero, l'ordine e il tipo dei parametri per il costruttore da ottenere. -or- Matrice vuota del tipo Type , ovvero tipi Type[] = Array.Empty{Type}()) per ottenere un costruttore che non accetta parametri. -o - EmptyTypes.

Restituisce

Oggetto ConstructorInfo che rappresenta il costruttore corrispondente ai requisiti specificati, se presente; in caso contrario, null.

Si applica a

GetConstructor(Type[])

Cerca un costruttore di istanza pubblica i cui parametri corrispondono ai tipi nella matrice specificata.

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

Parametri

types
Type[]

Matrice di oggetti Type che rappresentano il numero, l'ordine e il tipo dei parametri per il costruttore desiderato.

-oppure-

Matrice vuota di oggetti Type per ottenere un costruttore che non accetta parametri. Tale matrice vuota viene fornita dal campo staticEmptyTypes.

Restituisce

Oggetto che rappresenta il costruttore dell'istanza pubblica i cui parametri corrispondono ai tipi nella matrice del tipo di parametro, se presente; in caso contrario, null.

Implementazioni

Attributi

Eccezioni

types è null.

-oppure-

Uno degli elementi in types è null.

types è multidimensionale.

Esempio

Nell'esempio seguente viene ottenuto il tipo di MyClass, ottiene l'oggetto ConstructorInfo e viene visualizzata la firma del costruttore.

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

Commenti

Questo overload di metodo cerca costruttori di istanze pubbliche e non può essere usato per ottenere un inizializzatore di classe (costruttore statico). Per ottenere un inizializzatore di classi, usare un overload che accetta BindingFlagse specificare | BindingFlags.NonPublicBindingFlags.Static(BindingFlags.StaticOrBindingFlags.NonPublic in Visual Basic). È anche possibile ottenere l'inizializzatore di classe usando la TypeInitializer proprietà .

Se il costruttore richiesto non è pubblico, questo metodo restituisce null.

Nota

Non è possibile omettere i parametri durante la ricerca di costruttori e metodi. È possibile omettere solo i parametri quando si richiama.

Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce con ConstructorInfo i parametri di tipo sostituiti dagli argomenti di tipo appropriati. Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo generico o di un metodo generico, questo metodo restituisce nullsempre .

Vedi anche

Si applica a