Condividi tramite


Type.GetConstructor Metodo

Definizione

Ottiene un costruttore specifico dell'oggetto corrente Type.

Overload

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

Cerca un costruttore i cui parametri corrispondono ai tipi di argomento e ai modificatori specificati, utilizzando i vincoli di associazione specificati e la convenzione di chiamata specificata.

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

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

GetConstructor(BindingFlags, Type[])

Cerca un costruttore i cui parametri corrispondono ai tipi di argomento specificati, utilizzando 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[])

Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs

Cerca un costruttore i cui parametri corrispondono ai tipi di argomento e ai modificatori specificati, utilizzando i vincoli di associazione specificati e la convenzione di chiamata specificata.

public:
 System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, System::Reflection::CallingConventions callConvention, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public:
 virtual System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, System::Reflection::CallingConventions callConvention, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]
public System.Reflection.ConstructorInfo? GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.ConstructorInfo GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers);
public System.Reflection.ConstructorInfo? GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.ConstructorInfo GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)>]
member this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
member this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * System.Reflection.CallingConventions * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
Public Function GetConstructor (bindingAttr As BindingFlags, binder As Binder, callConvention As CallingConventions, types As Type(), modifiers As ParameterModifier()) As ConstructorInfo

Parametri

bindingAttr
BindingFlags

Combinazione bit per bit dei valori di enumerazione che specificano come viene eseguita la ricerca.

oppure

Default per restituire null.

binder
Binder

Oggetto che definisce un set di proprietà e abilita l'associazione, che può comportare la selezione di un metodo di overload, la coercizione dei tipi di argomento e la chiamata di un membro tramite reflection.

oppure

Riferimento Null (Nothing in Visual Basic) per utilizzare .DefaultBinder

callConvention
CallingConventions

Oggetto che specifica il set di regole da utilizzare per quanto riguarda l'ordine e il layout degli argomenti, il modo in cui viene passato il valore restituito, i registri usati per gli argomenti e lo stack viene pulito.

types
Type[]

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

oppure

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

modifiers
ParameterModifier[]

Matrice di ParameterModifier oggetti che rappresentano gli attributi associati all'elemento corrispondente nella types matrice. Il gestore di associazione predefinito non elabora questo parametro.

Restituisce

Oggetto che rappresenta il costruttore che soddisfa i requisiti specificati, se 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 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 modifiers), è possibile usare la classe astratta System.Reflection.Binder per scrivere un binder personalizzato che esegue l'elaborazione di modifiers. ParameterModifier viene utilizzato solo quando si esegue la chiamata tramite interoperabilità COM e vengono gestiti solo i parametri passati per riferimento.

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

I flag di filtro seguenti BindingFlags possono essere usati per definire i costruttori da 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 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 della classe base restituiti dai Get metodi quando si analizza un tipo.

Tipo di membro Statico Non statico
Costruttore No No
Campo No Sì. Un campo è sempre nascosto per nome e firma.
Event 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 (virtuale e non virtuale) può essere nascosto per nome o nascosto per nome e firma.
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. In riflessione, le proprietà e gli eventi sono hide-by-name-and-signature. Se si dispone di una proprietà con una funzione di accesso get e set nella classe base, 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 comune.

Annotazioni

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 ConstructorInfo con 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[])

Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs

Cerca un costruttore i cui parametri corrispondono ai tipi di argomento e ai modificatori specificati, 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);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]
public System.Reflection.ConstructorInfo? GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.ConstructorInfo GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers);
public System.Reflection.ConstructorInfo? GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.ConstructorInfo GetConstructor(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)>]
member this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
member this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
abstract member GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : System.Reflection.BindingFlags * System.Reflection.Binder * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.ConstructorInfo
Public Function GetConstructor (bindingAttr As BindingFlags, binder As Binder, types As Type(), modifiers As ParameterModifier()) As ConstructorInfo

Parametri

bindingAttr
BindingFlags

Combinazione bit per bit dei valori di enumerazione che specificano come viene eseguita la ricerca.

oppure

Default per restituire null.

binder
Binder

Oggetto che definisce un set di proprietà e abilita l'associazione, che può comportare la selezione di un metodo di overload, la coercizione dei tipi di argomento e la chiamata di un membro tramite reflection.

oppure

Riferimento Null (Nothing in Visual Basic) per utilizzare .DefaultBinder

types
Type[]

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

oppure

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

oppure

EmptyTypes.

modifiers
ParameterModifier[]

Matrice di ParameterModifier oggetti che rappresentano gli attributi associati all'elemento corrispondente nella matrice del tipo di parametro. Il gestore di associazione predefinito non elabora questo parametro.

Restituisce

Oggetto ConstructorInfo che rappresenta il costruttore che soddisfa i 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 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, tenterà binder di coercire i tipi di parametro specificati nella types matrice per selezionare una corrispondenza. Se non binder è possibile selezionare una corrispondenza, null viene restituito .

I flag di filtro seguenti BindingFlags possono essere usati per definire i costruttori da 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 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 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à .

Annotazioni

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 ConstructorInfo con 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[])

Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs

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

public:
 System::Reflection::ConstructorInfo ^ GetConstructor(System::Reflection::BindingFlags bindingAttr, cli::array <Type ^> ^ types);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]
public System.Reflection.ConstructorInfo? GetConstructor(System.Reflection.BindingFlags bindingAttr, Type[] types);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)>]
member this.GetConstructor : System.Reflection.BindingFlags * Type[] -> System.Reflection.ConstructorInfo
Public Function GetConstructor (bindingAttr As BindingFlags, types As Type()) As ConstructorInfo

Parametri

bindingAttr
BindingFlags

Combinazione bit per bit dei valori di enumerazione che specificano come viene eseguita la ricerca. -oppure- Valore predefinito 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. -oppure- Matrice vuota del tipo Type ,ovvero Type[] types = Array.Empty{Type}()) per ottenere un costruttore che non accetta parametri. -oppure- EmptyTypes.

Restituisce

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

Attributi

Si applica a

GetConstructor(Type[])

Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs
Origine:
Type.cs

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);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]
public System.Reflection.ConstructorInfo? GetConstructor(Type[] types);
public System.Reflection.ConstructorInfo GetConstructor(Type[] types);
public System.Reflection.ConstructorInfo? GetConstructor(Type[] types);
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.ConstructorInfo GetConstructor(Type[] types);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)>]
member this.GetConstructor : Type[] -> System.Reflection.ConstructorInfo
member this.GetConstructor : Type[] -> System.Reflection.ConstructorInfo
abstract member GetConstructor : Type[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : Type[] -> System.Reflection.ConstructorInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
abstract member GetConstructor : Type[] -> System.Reflection.ConstructorInfo
override this.GetConstructor : Type[] -> System.Reflection.ConstructorInfo
Public Function GetConstructor (types As Type()) As ConstructorInfo

Parametri

types
Type[]

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

oppure

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

Restituisce

Oggetto che rappresenta il costruttore dell'istanza pubblica i cui parametri corrispondono ai tipi nella matrice del tipo di parametro, se trovato; 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, viene ottenuto l'oggetto ConstructorInfo e viene visualizzata la firma del costruttore.

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 del metodo cerca costruttori di istanze pubbliche e non può essere usato per ottenere un inizializzatore di classe (costruttore statico). Per ottenere un inizializzatore di classe, 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.

Annotazioni

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 ConstructorInfo con 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