Type.GetConstructor Metodo
Definizione
Overload
GetConstructor(Type[]) |
Cerca un costruttore di istanza pubblica i cui parametri corrispondono ai tipi nella matrice specificata.Searches for a public instance constructor whose parameters match the types in the specified array. |
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.Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints. |
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.Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention. |
GetConstructor(Type[])
Cerca un costruttore di istanza pubblica i cui parametri corrispondono ai tipi nella matrice specificata.Searches for a public instance constructor whose parameters match the types in the specified array.
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.An array of Type objects representing the number, order, and type of the parameters for the desired constructor.
-oppure--or-
Matrice vuota di oggetti Type per ottenere un costruttore che non accetta parametri.An empty array of Type objects, to get a constructor that takes no parameters. Tale matrice vuota viene fornita dal campo static
EmptyTypes.Such an empty array is provided by the static
field EmptyTypes.
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
.An object representing the public instance constructor whose parameters match the types in the parameter type array, if found; otherwise, null
.
Implementazioni
- Attributi
Eccezioni
types
è null
.types
is null
.
-oppure--or-
Uno degli elementi in types
è null
.One of the elements in types
is null
.
types
è multidimensionale.types
is multidimensional.
Esempio
Nell'esempio seguente viene ottenuto il tipo di MyClass
, viene ottenuto l' ConstructorInfo oggetto e viene visualizzata la firma del costruttore.The following example obtains the type of MyClass
, gets the ConstructorInfo object, and displays the constructor signature.
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
Commenti
Questo overload del metodo cerca costruttori di istanza pubblici e non può essere usato per ottenere un inizializzatore di classe (costruttore statico).This method overload looks for public instance constructors and cannot be used to obtain a class initializer (static constructor). Per ottenere un inizializzatore di classe, usare un overload che accetta BindingFlags e specificare BindingFlags.Static | BindingFlags.NonPublic ( BindingFlags.Static Or
BindingFlags.NonPublic in Visual Basic).To get a class initializer, use an overload that takes BindingFlags, and specify BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOr
BindingFlags.NonPublic in Visual Basic). È anche possibile ottenere l'inizializzatore di classe usando la TypeInitializer Proprietà.You can also get the class initializer using the TypeInitializer property.
Se il costruttore richiesto non è pubblico, questo metodo restituisce null
.If the requested constructor is non-public, this method returns null
.
Nota
Non è possibile omettere i parametri durante la ricerca di costruttori e metodi.You cannot omit parameters when looking up constructors and methods. È possibile omettere solo i parametri quando si richiama.You can only omit parameters when invoking.
Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce l'oggetto ConstructorInfo con i parametri di tipo sostituiti dagli argomenti di tipo appropriati.If the current Type represents a constructed generic type, this method returns the ConstructorInfo with the type parameters replaced by the appropriate type arguments. Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo o di un metodo generico, questo metodo restituisce sempre null
.If the current Type represents a type parameter in the definition of a generic type or generic method, this method always returns null
.
Vedi anche
- ConstructorInfo
- DefaultBinder
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()
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.Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints.
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.A bitwise combination of the enumeration values that specify how the search is conducted.
-oppure--or-
Default per restituire null
.Default to return 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.An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.
-oppure--or-
Riferimento Null (Nothing
in Visual Basic) per l'uso di DefaultBinder.A null reference (Nothing
in Visual Basic), to use the DefaultBinder.
- types
- Type[]
Matrice di oggetti Type che rappresenta numero, ordine e tipo dei parametri relativi al costruttore da ottenere.An array of Type objects representing the number, order, and type of the parameters for the constructor to get.
-oppure--or- Matrice vuota di tipo Type (ovvero Type[] types = new Type[0]) per ottenere un costruttore che non accetta parametri.An empty array of the type Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
-oppure--or- EmptyTypes.EmptyTypes.
- modifiers
- ParameterModifier[]
Matrice di oggetti ParameterModifier che rappresentano gli attributi associati all'elemento corrispondente nella matrice del tipo di parametro.An array of ParameterModifier objects representing the attributes associated with the corresponding element in the parameter type array. Questo parametro non viene elaborato dal binder predefinito.The default binder does not process this parameter.
Restituisce
Oggetto ConstructorInfo che rappresenta il costruttore corrispondente ai requisiti specificati, se presente; in caso contrario, null
.A ConstructorInfo object representing the constructor that matches the specified requirements, if found; otherwise, null
.
Implementazioni
- Attributi
Eccezioni
types
è null
.types
is null
.
-oppure--or-
Uno degli elementi in types
è null
.One of the elements in types
is null
.
types
è multidimensionale.types
is multidimensional.
-oppure--or-
modifiers
è multidimensionale.modifiers
is multidimensional.
-oppure--or-
types
e modifiers
non hanno la stessa lunghezza.types
and modifiers
do not have the same length.
Esempio
Nell'esempio seguente viene ottenuto il tipo di MyClass
, viene ottenuto l' ConstructorInfo oggetto e viene visualizzata la firma del costruttore.The following example obtains the type of MyClass
, gets the ConstructorInfo object, and displays the constructor signature.
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
Commenti
Se non esiste una corrispondenza esatta, binder
tenterà di forzare i tipi di parametro specificati nella types
matrice per selezionare una corrispondenza.If an exact match does not exist, the binder
will attempt to coerce the parameter types specified in the types
array in order to select a match. Se binder
non è in grado di selezionare una corrispondenza, null
viene restituito.If the binder
is unable to select a match, then null
is returned.
I BindingFlags flag di filtro seguenti possono essere usati per definire i costruttori da includere nella ricerca:The following BindingFlags filter flags can be used to define which constructors to include in the search:
È necessario specificare
BindingFlags.Instance
o perBindingFlags.Static
ottenere un valore restituito.You must specify eitherBindingFlags.Instance
orBindingFlags.Static
in order to get a return.Specificare
BindingFlags.Public
per includere i costruttori pubblici nella ricerca.SpecifyBindingFlags.Public
to include public constructors in the search.Specificare
BindingFlags.NonPublic
per includere costruttori non pubblici (ovvero costruttori privati, interni e protetti) nella ricerca.SpecifyBindingFlags.NonPublic
to include non-public constructors (that is, private, internal, and protected constructors) in the search.
Per altre informazioni, vedere System.Reflection.BindingFlags.See System.Reflection.BindingFlags for more information.
Per ottenere l'inizializzatore di classe (costruttore statico) utilizzando questo overload del metodo, è necessario specificare BindingFlags.Static | BindingFlags.NonPublic ( BindingFlags.Static Or
BindingFlags.NonPublic in Visual Basic).To get the class initializer (static constructor) using this method overload, you must specify BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOr
BindingFlags.NonPublic in Visual Basic). È anche possibile ottenere l'inizializzatore di classe usando la TypeInitializer Proprietà.You can also get the class initializer using the TypeInitializer property.
Nota
Non è possibile omettere i parametri durante la ricerca di costruttori e metodi.You cannot omit parameters when looking up constructors and methods. È possibile omettere solo i parametri quando si richiama.You can only omit parameters when invoking.
Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce l'oggetto ConstructorInfo con i parametri di tipo sostituiti dagli argomenti di tipo appropriati.If the current Type represents a constructed generic type, this method returns the ConstructorInfo with the type parameters replaced by the appropriate type arguments. Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo o di un metodo generico, questo metodo restituisce sempre null
.If the current Type represents a type parameter in the definition of a generic type or generic method, this method always returns null
.
Vedi anche
- ConstructorInfo
- BindingFlags
- Binder
- DefaultBinder
- ParameterModifier
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()
Si applica a
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.Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
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.A bitwise combination of the enumeration values that specify how the search is conducted.
-oppure--or-
Default per restituire null
.Default to return 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.An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.
-oppure--or-
Riferimento Null (Nothing
in Visual Basic) per l'uso di DefaultBinder.A null reference (Nothing
in Visual Basic), to use the 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.The object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and the stack is cleaned up.
- types
- Type[]
Matrice di oggetti Type che rappresenta numero, ordine e tipo dei parametri relativi al costruttore da ottenere.An array of Type objects representing the number, order, and type of the parameters for the constructor to get.
-oppure--or- Matrice vuota di tipo Type (ovvero Type[] types = new Type[0]) per ottenere un costruttore che non accetta parametri.An empty array of the type Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
- modifiers
- ParameterModifier[]
Matrice di oggetti ParameterModifier che rappresentano gli attributi associati all'elemento corrispondente nella matrice types
.An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types
array. Questo parametro non viene elaborato dal binder predefinito.The default binder does not process this parameter.
Restituisce
Oggetto che rappresenta il costruttore corrispondente ai requisiti specificati, se è stato trovato; in caso contrario, null
.An object representing the constructor that matches the specified requirements, if found; otherwise, null
.
Implementazioni
- Attributi
Eccezioni
types
è null
.types
is null
.
-oppure--or-
Uno degli elementi in types
è null
.One of the elements in types
is null
.
types
è multidimensionale.types
is multidimensional.
-oppure--or-
modifiers
è multidimensionale.modifiers
is multidimensional.
-oppure--or-
types
e modifiers
non hanno la stessa lunghezza.types
and modifiers
do not have the same length.
Esempio
Nell'esempio seguente viene ottenuto il tipo di MyClass
, viene ottenuto l' ConstructorInfo oggetto e viene visualizzata la firma del costruttore.The following example obtains the type of MyClass
, gets the ConstructorInfo object, and displays the constructor signature.
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
Commenti
Sebbene il binder predefinito non elabori ParameterModifier (il modifiers
parametro), è possibile usare la classe astratta System.Reflection.Binder per scrivere un gestore di associazione personalizzato che esegue l'elaborazione modifiers
.Although the default binder does not process ParameterModifier (the modifiers
parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers
. ParameterModifier
viene utilizzato solo quando si effettua una chiamata tramite l'interoperabilità COM e vengono gestiti solo i parametri passati per riferimento.ParameterModifier
is only used when calling through COM interop, and only parameters that are passed by reference are handled.
Se non esiste una corrispondenza esatta, binder
tenterà di forzare i tipi di parametro specificati nella types
matrice per selezionare una corrispondenza.If an exact match does not exist, the binder
will attempt to coerce the parameter types specified in the types
array in order to select a match. Se binder
non è in grado di selezionare una corrispondenza, null
viene restituito.If the binder
is unable to select a match, then null
is returned.
I BindingFlags flag di filtro seguenti possono essere usati per definire i costruttori da includere nella ricerca:The following BindingFlags filter flags can be used to define which constructors to include in the search:
È necessario specificare
BindingFlags.Instance
o perBindingFlags.Static
ottenere un valore restituito.You must specify eitherBindingFlags.Instance
orBindingFlags.Static
in order to get a return.Specificare
BindingFlags.Public
per includere i costruttori pubblici nella ricerca.SpecifyBindingFlags.Public
to include public constructors in the search.Specificare
BindingFlags.NonPublic
per includere costruttori non pubblici (ovvero costruttori privati, interni e protetti) nella ricerca.SpecifyBindingFlags.NonPublic
to include non-public constructors (that is, private, internal, and protected constructors) in the search.
Per altre informazioni, vedere System.Reflection.BindingFlags.See System.Reflection.BindingFlags for more information.
Per ottenere l'inizializzatore di classe (costruttore statico) utilizzando questo metodo, è necessario specificare BindingFlags.Static | BindingFlags.NonPublic ( BindingFlags.Static Or
BindingFlags.NonPublic in Visual Basic).To get the class initializer (static constructor) using this method, you must specify BindingFlags.Static | BindingFlags.NonPublic (BindingFlags.StaticOr
BindingFlags.NonPublic in Visual Basic). È anche possibile ottenere l'inizializzatore di classe usando la TypeInitializer Proprietà.You can also get the class initializer using the TypeInitializer property.
La tabella seguente mostra quali membri di una classe di base vengono restituiti dai Get
metodi durante la reflection su un tipo.The following table shows what members of a base class are returned by the Get
methods when reflecting on a type.
Tipo di membroMember Type | StaticStatic | Non staticoNon-Static |
---|---|---|
CostruttoreConstructor | NoNo | NoNo |
CampoField | NoNo | Sì.Yes. Un campo è sempre nascosto per nome e firma.A field is always hide-by-name-and-signature. |
EventoEvent | Non applicabileNot applicable | La regola Common Type System è che l'ereditarietà è identica a quella dei metodi che implementano la proprietà.The common type system rule is that the inheritance is the same as that of the methods that implement the property. La reflection considera le proprietà come nascoste per nome e firma.Reflection treats properties as hide-by-name-and-signature. Vedere la nota 2 di seguito.See note 2 below. |
MetodoMethod | NoNo | Sì.Yes. Un metodo (sia virtuale che non virtuale) può essere nascosto in base al nome o nascosto per nome e firma.A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Tipo annidatoNested Type | NoNo | NoNo |
ProprietàProperty | Non applicabileNot applicable | La regola Common Type System è che l'ereditarietà è identica a quella dei metodi che implementano la proprietà.The common type system rule is that the inheritance is the same as that of the methods that implement the property. La reflection considera le proprietà come nascoste per nome e firma.Reflection treats properties as hide-by-name-and-signature. Vedere la nota 2 di seguito.See note 2 below. |
Hide-by-Name-and-signature prende in considerazione tutte le parti della firma, inclusi i modificatori personalizzati, i tipi restituiti, i tipi di parametro, le sentinelle e le convenzioni di chiamata non gestite.Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. Si tratta di un confronto binario.This is a binary comparison.
Per la reflection, le proprietà e gli eventi sono nascosti per nome e firma.For reflection, properties and events are hide-by-name-and-signature. Se si dispone di una proprietà con una funzione di accesso get e set nella classe di base, ma la classe derivata dispone solo di una funzione di accesso get, la proprietà della classe derivata nasconde la proprietà della classe base e non sarà possibile accedere al setter sulla classe di base.If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
Gli attributi personalizzati non fanno parte del Common Type System.Custom attributes are not part of the common type system.
Nota
Non è possibile omettere i parametri durante la ricerca di costruttori e metodi.You cannot omit parameters when looking up constructors and methods. È possibile omettere solo i parametri quando si richiama.You can only omit parameters when invoking.
Se l'oggetto corrente Type rappresenta un tipo generico costruito, questo metodo restituisce l'oggetto ConstructorInfo con i parametri di tipo sostituiti dagli argomenti di tipo appropriati.If the current Type represents a constructed generic type, this method returns the ConstructorInfo with the type parameters replaced by the appropriate type arguments. Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo o di un metodo generico, questo metodo restituisce sempre null
.If the current Type represents a type parameter in the definition of a generic type or generic method, this method always returns null
.
Vedi anche
- ConstructorInfo
- BindingFlags
- Binder
- DefaultBinder
- CallingConventions
- ParameterModifier
- GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])
- GetConstructors()