Type.InvokeMember Metodo
Definizione
Overload
InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]) |
Quando ne viene eseguito l'override in una classe derivata, richiama il membro specificato, usando i vincoli di binding specificati e associando l'elenco di argomenti, i modificatori e le impostazioni cultura specificati.When overridden in a derived class, invokes the specified member, using the specified binding constraints and matching the specified argument list, modifiers and culture. |
InvokeMember(String, BindingFlags, Binder, Object, Object[]) |
Chiama il membro specificato, usando i vincoli di associazione specificati e associando l'elenco di argomenti specificato.Invokes the specified member, using the specified binding constraints and matching the specified argument list. |
InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo) |
Chiama il membro specificato, usando i vincoli di binding specificati e associando l'elenco di argomenti specificati e le impostazioni cultura.Invokes the specified member, using the specified binding constraints and matching the specified argument list and culture. |
InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])
Quando ne viene eseguito l'override in una classe derivata, richiama il membro specificato, usando i vincoli di binding specificati e associando l'elenco di argomenti, i modificatori e le impostazioni cultura specificati.When overridden in a derived class, invokes the specified member, using the specified binding constraints and matching the specified argument list, modifiers and culture.
public:
abstract System::Object ^ InvokeMember(System::String ^ name, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, System::Object ^ target, cli::array <System::Object ^> ^ args, cli::array <System::Reflection::ParameterModifier> ^ modifiers, System::Globalization::CultureInfo ^ culture, cli::array <System::String ^> ^ namedParameters);
public abstract object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters);
abstract member InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] * System.Reflection.ParameterModifier[] * System.Globalization.CultureInfo * string[] -> obj
Parametri
- name
- String
Stringa che contiene il nome del costruttore, del metodo, della proprietà o del membro del campo da richiamare.The string containing the name of the constructor, method, property, or field member to invoke.
In alternativa-or- Stringa vuota ("") per richiamare il membro predefinito.An empty string ("") to invoke the default member.
In alternativa-or-
Per i membri IDispatch
, stringa che rappresenta DispID, ad esempio "[DispID=3]".For IDispatch
members, a string representing the DispID, for example "[DispID=3]".
- invokeAttr
- 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. L'accesso può essere uno dei BindingFlags
, ad esempio Public
, NonPublic
, Private
, InvokeMethod
, GetField
e così via.The access can be one of the BindingFlags
such as Public
, NonPublic
, Private
, InvokeMethod
, GetField
, and so on. Il tipo di ricerca non deve essere specificato.The type of lookup need not be specified. Se il tipo di ricerca viene omesso, vengono usati BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.Static
.If the type of lookup is omitted, BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.Static
are used.
- 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. Si noti che potrebbe essere necessario definire in modo esplicito un oggetto Binder per richiamare correttamente overload di metodo con argomenti variabili.Note that explicitly defining a Binder object may be required for successfully invoking method overloads with variable arguments.
- target
- Object
Oggetto su cui richiamare il membro specificato.The object on which to invoke the specified member.
- args
- Object[]
Matrice che contiene gli argomenti da passare al membro da richiamare.An array containing the arguments to pass to the member to invoke.
- modifiers
- ParameterModifier[]
Matrice di oggetti ParameterModifier che rappresentano gli attributi associati all'elemento corrispondente nella matrice args
.An array of ParameterModifier objects representing the attributes associated with the corresponding element in the args
array. Gli attributi associati di un parametro sono archiviati nella firma digitale del membro.A parameter's associated attributes are stored in the member's signature.
Il binder predefinito elabora questo parametro solo quando si chiama un componente COM.The default binder processes this parameter only when calling a COM component.
- culture
- CultureInfo
Oggetto CultureInfo che rappresenta le impostazioni locali da usare, che possono essere necessarie per conversioni specifiche delle impostazioni locali, ad esempio la conversione di un valore numerico da String a Double.The CultureInfo object representing the globalization locale to use, which may be necessary for locale-specific conversions, such as converting a numeric String to a Double.
In alternativa-or-
Riferimento Null (Nothing
in Visual Basic) per l'uso dell'oggetto CultureInfo del thread corrente.A null reference (Nothing
in Visual Basic) to use the current thread's CultureInfo.
- namedParameters
- String[]
Matrice contenente i nomi dei parametri a cui sono passati i valori nella matrice args
.An array containing the names of the parameters to which the values in the args
array are passed.
Restituisce
Oggetto che rappresenta il valore restituito di un membro richiamato.An object representing the return value of the invoked member.
Implementazioni
Eccezioni
invokeAttr
non contiene CreateInstance
e name
è null
.invokeAttr
does not contain CreateInstance
and name
is null
.
args
e modifiers
non hanno la stessa lunghezza.args
and modifiers
do not have the same length.
-oppure--or-
invokeAttr
non è un attributo valido di BindingFlags .invokeAttr
is not a valid BindingFlags attribute.
-oppure--or-
invokeAttr
non contiene uno dei flag di binding seguenti: InvokeMethod
, CreateInstance
, GetField
, SetField
, GetProperty
o SetProperty
.invokeAttr
does not contain one of the following binding flags: InvokeMethod
, CreateInstance
, GetField
, SetField
, GetProperty
, or SetProperty
.
-oppure--or-
invokeAttr
contiene CreateInstance
in combinazione con InvokeMethod
, GetField
, SetField
, GetProperty
o SetProperty
.invokeAttr
contains CreateInstance
combined with InvokeMethod
, GetField
, SetField
, GetProperty
, or SetProperty
.
In alternativa-or-
invokeAttr
contiene sia GetField
che SetField
.invokeAttr
contains both GetField
and SetField
.
-oppure--or-
invokeAttr
contiene sia GetProperty
che SetProperty
.invokeAttr
contains both GetProperty
and SetProperty
.
-oppure--or-
invokeAttr
contiene InvokeMethod
in combinazione con SetField
o SetProperty
.invokeAttr
contains InvokeMethod
combined with SetField
or SetProperty
.
-oppure--or-
invokeAttr
contiene SetField
e args
include più elementi.invokeAttr
contains SetField
and args
has more than one element.
-oppure--or- La matrice di parametri denominata è più grande della matrice di argomenti.The named parameter array is larger than the argument array.
-oppure--or-
Questo metodo è stato chiamato su un oggetto COM e uno dei flag di binding seguenti non è stato passato: BindingFlags.InvokeMethod
, BindingFlags.GetProperty
, BindingFlags.SetProperty
, BindingFlags.PutDispProperty
o BindingFlags.PutRefDispProperty
.This method is called on a COM object and one of the following binding flags was not passed in: BindingFlags.InvokeMethod
, BindingFlags.GetProperty
, BindingFlags.SetProperty
, BindingFlags.PutDispProperty
, or BindingFlags.PutRefDispProperty
.
In alternativa-or-
Una delle matrici di parametri denominati contiene una stringa null
.One of the named parameter arrays contains a string that is null
.
Il membro specificato è un inizializzatore di classi.The specified member is a class initializer.
Non è possibile trovare il campo o la proprietà.The field or property cannot be found.
Non è possibile trovare metodi corrispondenti agli argomenti in args
.No method can be found that matches the arguments in args
.
In alternativa-or-
Non è possibile trovare membri con i nomi di argomento forniti in namedParameters
.No member can be found that has the argument names supplied in namedParameters
.
In alternativa-or-
L'oggetto Type corrente rappresenta un tipo che contiene parametri di tipo open, ovvero ContainsGenericParameters restituisce true
.The current Type object represents a type that contains open type parameters, that is, ContainsGenericParameters returns true
.
Non è possibile richiamare il metodo specificato su target
.The specified member cannot be invoked on target
.
Più di un metodo corrisponde ai criteri di binding.More than one method matches the binding criteria.
Il metodo rappresentato da name
include uno o più parametri di tipo generico non specificati.The method represented by name
has one or more unspecified generic type parameters. In altri termini, la proprietà ContainsGenericParameters del metodo restituisce true
.That is, the method's ContainsGenericParameters property returns true
.
Commenti
InvokeMember
chiama un membro del costruttore o un membro del metodo, ottiene o imposta un membro della proprietà, ottiene o imposta un membro del campo dati oppure ottiene o imposta un elemento di un membro di matrice.InvokeMember
calls a constructor member or a method member, gets or sets a property member, gets or sets a data field member, or gets or sets an element of an array member.
Nota
Non è possibile InvokeMember utilizzare per richiamare un metodo generico.You cannot use InvokeMember to invoke a generic method.
Quando si richiama un IDispatch
membro è possibile specificare il DISPID anziché il nome del membro, usando il formato stringa "[DISPID = # #]".When you invoke an IDispatch
member you can specify the DispID instead of the member name, using the string format "[DispID=##]". Se, ad esempio, il DispID di MyComMethod è 3, è possibile specificare la stringa "[DispID = 3]" anziché "MyComMethod".For example, if the DispID of MyComMethod is 3, you can specify the string "[DispID=3]" instead of "MyComMethod". La chiamata di un membro tramite DispID è più veloce rispetto alla ricerca del membro in base al nome.Invoking a member by DispID is faster than looking up the member by name. Negli scenari di aggregazione complessi, il DispID è talvolta l'unico modo per richiamare il membro desiderato.In complex aggregation scenarios, the DispID is sometimes the only way to invoke the desired member.
Sebbene il binder predefinito non elabori ParameterModifier o CultureInfo (i modifiers
parametri e culture
), è possibile usare la classe astratta System.Reflection.Binder per scrivere un gestore di associazione personalizzato che elabora modifiers
e culture
.Although the default binder does not process ParameterModifier or CultureInfo (the modifiers
and culture
parameters), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers
and culture
. 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.
Tutti i parametri nella matrice namedParameters
ottengono il valore nell'elemento corrispondente della matrice args
.Each parameter in the namedParameters
array gets the value in the corresponding element in the args
array. Se la lunghezza di args
è superiore a quella di namedParameters
, i valori degli argomenti rimanenti vengono passati in ordine.If the length of args
is greater than the length of namedParameters
, the remaining argument values are passed in order.
La namedParameters
matrice può essere utilizzata per modificare l'ordine degli argomenti in una matrice di input.The namedParameters
array can be used to change the order of arguments in an input array. M(string a, int b)
Dato il metodo (M(ByVal a As String, ByVal b As Integer)
in Visual Basic) e la matrice { 42, "x" }
di input, ad esempio, la matrice di input può essere passata senza modifiche args
a se la { "b", "a" }
matrice viene fornita namedParameters
per.For example, given the method M(string a, int b)
(M(ByVal a As String, ByVal b As Integer)
in Visual Basic) and the input array { 42, "x" }
, the input array can be passed unchanged to args
if the array { "b", "a" }
is supplied for namedParameters
.
I flag BindingFlags di filtro seguenti possono essere usati per definire i membri da includere nella ricerca:The following BindingFlags filter flags can be used to define which members to include in the search:
Consente
BindingFlags.Public
di specificare di includere i membri pubblici nella ricerca.SpecifyBindingFlags.Public
to include public members in the search.Specificare
BindingFlags.NonPublic
per includere i membri non pubblici (ovvero i membri privati, interni e protetti) nella ricerca.SpecifyBindingFlags.NonPublic
to include non-public members (that is, private, internal, and protected members) in the search.Specificare
BindingFlags.FlattenHierarchy
per includere i membri statici nella gerarchia.SpecifyBindingFlags.FlattenHierarchy
to include static members up the hierarchy.
I flag BindingFlags di modifica seguenti possono essere utilizzati per modificare il funzionamento della ricerca:The following BindingFlags modifier flags can be used to change how the search works:
BindingFlags.IgnoreCase
per ignorare la distinzione traname
maiuscole e minuscole.BindingFlags.IgnoreCase
to ignore the case ofname
.BindingFlags.DeclaredOnly
per cercare solo i membri dichiarati Typein, non i membri che sono stati semplicemente ereditati.BindingFlags.DeclaredOnly
to search only the members declared on the Type, not members that were simply inherited.
I flag BindingFlags di chiamata seguenti possono essere usati per indicare l'azione da eseguire con il membro:The following BindingFlags invocation flags can be used to denote what action to take with the member:
CreateInstance
per richiamare un costruttore.CreateInstance
to invoke a constructor.name
viene ignorato.name
is ignored. Non valido con altri flag di chiamata.Not valid with other invocation flags.InvokeMethod
per richiamare un metodo, ma non un costruttore o un inizializzatore di tipo.InvokeMethod
to invoke a method, but not a constructor or a type initializer. Non valido conSetField
oSetProperty
.Not valid withSetField
orSetProperty
. SeInvokeMethod
viene specificato da soloBindingFlags.Instance
,BindingFlags.Public
, eBindingFlags.Static
vengono inclusi automaticamente.IfInvokeMethod
is specified by itself,BindingFlags.Public
,BindingFlags.Instance
, andBindingFlags.Static
are automatically included.GetField
per ottenere il valore di un campo.GetField
to get the value of a field. Non valido conSetField
.Not valid withSetField
.SetField
per impostare il valore di un campo.SetField
to set the value of a field. Non valido conGetField
.Not valid withGetField
.GetProperty
per ottenere una proprietà.GetProperty
to get a property. Non valido conSetProperty
.Not valid withSetProperty
.SetProperty
per impostare una proprietà.SetProperty
to set a property. Non valido conGetProperty
.Not valid withGetProperty
.
Per altre informazioni, vedere System.Reflection.BindingFlags.See System.Reflection.BindingFlags for more information.
Viene richiamato un metodo se si verificano entrambe le condizioni seguenti:A method will be invoked if both of the following conditions are true:
Il numero di parametri nella dichiarazione di metodo è uguale al numero di argomenti nella
args
matrice (a meno che non siano definiti argomenti predefiniti per il membro eBindingFlags.OptionalParamBinding
che sia specificato).The number of parameters in the method declaration equals the number of arguments in theargs
array (unless default arguments are defined on the member andBindingFlags.OptionalParamBinding
is specified).Il tipo di ogni argomento può essere convertito dal gestore di associazione al tipo del parametro.The type of each argument can be converted by the binder to the type of the parameter.
Il Binder troverà tutti i metodi corrispondenti.The binder will find all of the matching methods. Questi metodi si basano sul tipo di binding richiesto (BindingFlags valori InvokeMethod
, GetProperty
e così via).These methods are found based upon the type of binding requested (BindingFlags values InvokeMethod
, GetProperty
, and so on). Il set di metodi viene filtrato in base al nome, al numero di argomenti e a un set di modificatori di ricerca definiti nel gestore di associazione.The set of methods is filtered by the name, number of arguments, and a set of search modifiers defined in the binder.
Una volta selezionato, il metodo viene richiamato.After the method is selected, it is invoked. L'accessibilità viene controllata a questo punto.Accessibility is checked at that point. La ricerca può controllare il set di metodi in base all'attributo di accessibilità associato al metodo.The search may control which set of methods are searched based upon the accessibility attribute associated with the method. Il Binder.BindToMethod metodoBinder della classe è responsabile della selezione del metodo da richiamare.The Binder.BindToMethod method of the Binder class is responsible for selecting the method to be invoked. Il binder predefinito seleziona la corrispondenza più specifica.The default binder selects the most specific match.
InvokeMember
può essere usato per richiamare i metodi con parametri che hanno valori predefiniti.InvokeMember
can be used to invoke methods with parameters that have default values. Per eseguire l'associazione a questi metodi, BindingFlags.OptionalParamBinding è necessario specificare la reflection.To bind to these methods, Reflection requires BindingFlags.OptionalParamBinding to be specified. Per un parametro con un valore predefinito, è possibile specificare un valore diverso o fornire Missing.Value per usare il valore predefinito.For a parameter that has a default value, you can either supply a different value, or supply Missing.Value to use the default value.
Si consideri, ad esempio, un metodo come MyMethod (int x, float y = 2,0).For example, consider a method such as MyMethod(int x, float y = 2.0). Per richiamare questo metodo solo con il primo argomento come MyMethod (4), passare uno dei flag di binding precedenti e passare due argomenti, ovvero 4 per il primo argomento e Missing.Value
per il secondo argomento.To invoke this method with only the first argument as MyMethod(4), pass one of the above binding flags and pass two arguments, namely, 4 for the first argument and Missing.Value
for the second argument. A meno che non Missing.Value
si usi, non è possibile omettere i Invoke
parametri facoltativi con il metodo.Unless you use Missing.Value
, you may not omit optional parameters with the Invoke
method. Se necessario, usare InvokeMember
invece.If you must do so, use InvokeMember
instead.
Le restrizioni di accesso vengono ignorate per il codice completamente attendibile; ovvero, i costruttori privati, i metodi, i campi e le proprietà possono essere accessibili e richiamati tramite System.Reflection ogni volta che il codice è completamente attendibile.Access restrictions are ignored for fully trusted code; that is, private constructors, methods, fields, and properties can be accessed and invoked through System.Reflection whenever the code is fully trusted.
È possibile utilizzare Type.InvokeMember
per impostare un campo su un valore specifico specificando BindingFlags.SetField.You can use Type.InvokeMember
to set a field to a particular value by specifying BindingFlags.SetField. Se, ad esempio, si vuole impostare un campo di istanza pubblica denominato F nella classe C e f è un String
, è possibile usare codice come il seguente:For example, if you want to set a public instance field named F on class C, and F is a String
, you can use code such as:
typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {"strings new value"}, null, null, null);
Se F è un String[]
, è possibile usare codice come il seguente:If F is a String[]
, you can use code such as:
typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {new String[]{"a","z","c","d"}}, null, null, null);
che consente di inizializzare il campo F nella nuova matrice.which will initialize the field F to this new array. È anche possibile usare Type.InvokeMember
per impostare una posizione in una matrice fornendo l'indice del valore e quindi il valore successivo usando un codice simile al seguente:You can also use Type.InvokeMember
to set a position in an array by supplying the index of the value and then the next value by using code such as the following:
typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {1, "b"}, null, null, null);
In questo modo verrà modificata la stringa "z" nella matrice che F viene mantenuta nella stringa "b".This will change string "z" in the array that F holds to string "b".
Nota
A partire da .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a membri non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei membri non pubblici è limitato al set di concessioni del chiamante o a un subset loro.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. Vedere considerazioni sulla sicurezza per la reflection.(See Security Considerations for Reflection.)
Per usare questa funzionalità, l'applicazione deve essere destinata a .NET Framework 3.5.NET Framework 3.5 o versione successiva.To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.
Sicurezza
ReflectionPermission
per accedere ai membri non pubblici indipendentemente dal set di concessioni.for accessing non-public members regardless of their grant set. Enumerazione associata:MemberAccessAssociated enumeration: MemberAccess
SecurityPermission
per chiamare codice non gestito.to call unmanaged code. Enumerazione associata:UnmanagedCodeAssociated enumeration: UnmanagedCode
Vedi anche
InvokeMember(String, BindingFlags, Binder, Object, Object[])
Chiama il membro specificato, usando i vincoli di associazione specificati e associando l'elenco di argomenti specificato.Invokes the specified member, using the specified binding constraints and matching the specified argument list.
public:
virtual System::Object ^ InvokeMember(System::String ^ name, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, System::Object ^ target, cli::array <System::Object ^> ^ args);
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args);
abstract member InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] -> obj
override this.InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] -> obj
Parametri
- name
- String
Stringa che contiene il nome del costruttore, del metodo, della proprietà o del membro del campo da richiamare.The string containing the name of the constructor, method, property, or field member to invoke.
In alternativa-or- Stringa vuota ("") per richiamare il membro predefinito.An empty string ("") to invoke the default member.
In alternativa-or-
Per i membri IDispatch
, stringa che rappresenta DispID, ad esempio "[DispID=3]".For IDispatch
members, a string representing the DispID, for example "[DispID=3]".
- invokeAttr
- 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. L'accesso può essere uno dei BindingFlags
, ad esempio Public
, NonPublic
, Private
, InvokeMethod
, GetField
e così via.The access can be one of the BindingFlags
such as Public
, NonPublic
, Private
, InvokeMethod
, GetField
, and so on. Il tipo di ricerca non deve essere specificato.The type of lookup need not be specified. Se il tipo di ricerca viene omesso, vengono usati BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.Static
.If the type of lookup is omitted, BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.Static
are used.
- 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. Si noti che potrebbe essere necessario definire in modo esplicito un oggetto Binder per richiamare correttamente overload di metodo con argomenti variabili.Note that explicitly defining a Binder object may be required for successfully invoking method overloads with variable arguments.
- target
- Object
Oggetto su cui richiamare il membro specificato.The object on which to invoke the specified member.
- args
- Object[]
Matrice che contiene gli argomenti da passare al membro da richiamare.An array containing the arguments to pass to the member to invoke.
Restituisce
Oggetto che rappresenta il valore restituito di un membro richiamato.An object representing the return value of the invoked member.
Implementazioni
Eccezioni
invokeAttr
non contiene CreateInstance
e name
è null
.invokeAttr
does not contain CreateInstance
and name
is null
.
invokeAttr
non è un attributo valido di BindingFlags.invokeAttr
is not a valid BindingFlags attribute.
In alternativa-or-
invokeAttr
non contiene uno dei flag di binding seguenti: InvokeMethod
, CreateInstance
, GetField
, SetField
, GetProperty
o SetProperty
.invokeAttr
does not contain one of the following binding flags: InvokeMethod
, CreateInstance
, GetField
, SetField
, GetProperty
, or SetProperty
.
-oppure--or-
invokeAttr
contiene CreateInstance
in combinazione con InvokeMethod
, GetField
, SetField
, GetProperty
o SetProperty
.invokeAttr
contains CreateInstance
combined with InvokeMethod
, GetField
, SetField
, GetProperty
, or SetProperty
.
-oppure--or-
invokeAttr
contiene sia GetField
che SetField
.invokeAttr
contains both GetField
and SetField
.
In alternativa-or-
invokeAttr
contiene sia GetProperty
che SetProperty
.invokeAttr
contains both GetProperty
and SetProperty
.
-oppure--or-
invokeAttr
contiene InvokeMethod
in combinazione con SetField
o SetProperty
.invokeAttr
contains InvokeMethod
combined with SetField
or SetProperty
.
-oppure--or-
invokeAttr
contiene SetField
e args
include più elementi.invokeAttr
contains SetField
and args
has more than one element.
-oppure--or-
Questo metodo è stato chiamato su un oggetto COM e uno dei flag di binding seguenti non è stato passato: BindingFlags.InvokeMethod
, BindingFlags.GetProperty
, BindingFlags.SetProperty
, BindingFlags.PutDispProperty
o BindingFlags.PutRefDispProperty
.This method is called on a COM object and one of the following binding flags was not passed in: BindingFlags.InvokeMethod
, BindingFlags.GetProperty
, BindingFlags.SetProperty
, BindingFlags.PutDispProperty
, or BindingFlags.PutRefDispProperty
.
In alternativa-or-
Una delle matrici di parametri denominati contiene una stringa null
.One of the named parameter arrays contains a string that is null
.
Il membro specificato è un inizializzatore di classi.The specified member is a class initializer.
Non è possibile trovare il campo o la proprietà.The field or property cannot be found.
Non è possibile trovare metodi corrispondenti agli argomenti in args
.No method can be found that matches the arguments in args
.
-oppure--or-
L'oggetto Type corrente rappresenta un tipo che contiene parametri di tipo open, ovvero ContainsGenericParameters restituisce true
.The current Type object represents a type that contains open type parameters, that is, ContainsGenericParameters returns true
.
Non è possibile richiamare il metodo specificato su target
.The specified member cannot be invoked on target
.
Più di un metodo corrisponde ai criteri di binding.More than one method matches the binding criteria.
Questo metodo non è attualmente supportato in .NET Compact Framework.The .NET Compact Framework does not currently support this method.
Il metodo rappresentato da name
include uno o più parametri di tipo generico non specificati.The method represented by name
has one or more unspecified generic type parameters. In altri termini, la proprietà ContainsGenericParameters del metodo restituisce true
.That is, the method's ContainsGenericParameters property returns true
.
Esempi
Nell'esempio seguente viene InvokeMember
usato per accedere ai membri di un tipo.The following example uses InvokeMember
to access members of a type.
using namespace System;
using namespace System::Reflection;
// This sample class has a field, constructor, method, and property.
ref class MyType
{
private:
Int32 myField;
public:
MyType( interior_ptr<Int32> x )
{
*x *= 5;
}
virtual String^ ToString() override
{
return myField.ToString();
}
property Int32 MyProp
{
Int32 get()
{
return myField;
}
void set( Int32 value )
{
if ( value < 1 )
throw gcnew ArgumentOutOfRangeException( "value",value,"value must be > 0" );
myField = value;
}
}
};
int main()
{
Type^ t = MyType::typeid;
// Create an instance of a type.
array<Object^>^args = {8};
Console::WriteLine( "The value of x before the constructor is called is {0}.", args[ 0 ] );
Object^ obj = t->InvokeMember( nullptr, static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::CreateInstance), nullptr, nullptr, args );
Console::WriteLine( "Type: {0}", obj->GetType() );
Console::WriteLine( "The value of x after the constructor returns is {0}.", args[ 0 ] );
// Read and write to a field.
array<Object^>^obj5 = {5};
t->InvokeMember( "myField", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::SetField), nullptr, obj, obj5 );
Int32 v = safe_cast<Int32>(t->InvokeMember( "myField", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::GetField), nullptr, obj, nullptr ));
Console::WriteLine( "myField: {0}", v );
// Call a method.
String^ s = safe_cast<String^>(t->InvokeMember( "ToString", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::InvokeMethod), nullptr, obj, nullptr ));
Console::WriteLine( "ToString: {0}", s );
// Read and write a property. First, attempt to assign an
// invalid value; then assign a valid value; finally, get
// the value.
try
{
// Assign the value zero to MyProp. The Property Set
// throws an exception, because zero is an invalid value.
// InvokeMember catches the exception, and throws
// TargetInvocationException. To discover the real cause
// you must catch TargetInvocationException and examine
// the inner exception.
array<Object^>^obj0 = {(int^)0};
t->InvokeMember( "MyProp", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::SetProperty), nullptr, obj, obj0 );
}
catch ( TargetInvocationException^ e )
{
// If the property assignment failed for some unexpected
// reason, rethrow the TargetInvocationException.
if ( e->InnerException->GetType() != ArgumentOutOfRangeException::typeid )
throw;
Console::WriteLine( "An invalid value was assigned to MyProp." );
}
array<Object^>^obj2 = {2};
t->InvokeMember( "MyProp", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::SetProperty), nullptr, obj, obj2 );
v = safe_cast<Int32>(t->InvokeMember( "MyProp", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::GetProperty), nullptr, obj, nullptr ));
Console::WriteLine( "MyProp: {0}", v );
}
using System;
using System.Reflection;
// This sample class has a field, constructor, method, and property.
class MyType
{
Int32 myField;
public MyType(ref Int32 x) {x *= 5;}
public override String ToString() {return myField.ToString();}
public Int32 MyProp
{
get {return myField;}
set
{
if (value < 1)
throw new ArgumentOutOfRangeException("value", value, "value must be > 0");
myField = value;
}
}
}
class MyApp
{
static void Main()
{
Type t = typeof(MyType);
// Create an instance of a type.
Object[] args = new Object[] {8};
Console.WriteLine("The value of x before the constructor is called is {0}.", args[0]);
Object obj = t.InvokeMember(null,
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args);
Console.WriteLine("Type: " + obj.GetType().ToString());
Console.WriteLine("The value of x after the constructor returns is {0}.", args[0]);
// Read and write to a field.
t.InvokeMember("myField",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetField, null, obj, new Object[] {5});
Int32 v = (Int32) t.InvokeMember("myField",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetField, null, obj, null);
Console.WriteLine("myField: " + v);
// Call a method.
String s = (String) t.InvokeMember("ToString",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, null);
Console.WriteLine("ToString: " + s);
// Read and write a property. First, attempt to assign an
// invalid value; then assign a valid value; finally, get
// the value.
try
{
// Assign the value zero to MyProp. The Property Set
// throws an exception, because zero is an invalid value.
// InvokeMember catches the exception, and throws
// TargetInvocationException. To discover the real cause
// you must catch TargetInvocationException and examine
// the inner exception.
t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {0});
}
catch (TargetInvocationException e)
{
// If the property assignment failed for some unexpected
// reason, rethrow the TargetInvocationException.
if (e.InnerException.GetType() !=
typeof(ArgumentOutOfRangeException))
throw;
Console.WriteLine("An invalid value was assigned to MyProp.");
}
t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {2});
v = (Int32) t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, obj, null);
Console.WriteLine("MyProp: " + v);
}
}
Imports System.Reflection
' This sample class has a field, constructor, method, and property.
Class MyType
Private myField As Int32
Public Sub New(ByRef x As Int32)
x *= 5
End Sub
Public Overrides Function ToString() As [String]
Return myField.ToString()
End Function 'ToString
Public Property MyProp() As Int32
Get
Return myField
End Get
Set(ByVal Value As Int32)
If Value < 1 Then
Throw New ArgumentOutOfRangeException("value", Value, "value must be > 0")
End If
myField = Value
End Set
End Property
End Class
Class MyApp
Shared Sub Main()
Dim t As Type = GetType(MyType)
' Create an instance of a type.
Dim args() As [Object] = {8}
Console.WriteLine("The value of x before the constructor is called is {0}.", args(0))
Dim obj As [Object] = t.InvokeMember(Nothing, BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.CreateInstance, Nothing, Nothing, args)
Console.WriteLine("Type: {0}", obj.GetType().ToString())
Console.WriteLine("The value of x after the constructor returns is {0}.", args(0))
' Read and write to a field.
t.InvokeMember("myField", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.SetField, Nothing, obj, New [Object]() {5})
Dim v As Int32 = CType(t.InvokeMember("myField", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.GetField, Nothing, obj, Nothing), Int32)
Console.WriteLine("myField: {0}", v)
' Call a method.
Dim s As [String] = CType(t.InvokeMember("ToString", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.InvokeMethod, Nothing, obj, Nothing), [String])
Console.WriteLine("ToString: {0}", s)
' Read and write a property. First, attempt to assign an
' invalid value; then assign a valid value; finally, get
' the value.
Try
' Assign the value zero to MyProp. The Property Set
' throws an exception, because zero is an invalid value.
' InvokeMember catches the exception, and throws
' TargetInvocationException. To discover the real cause
' you must catch TargetInvocationException and examine
' the inner exception.
t.InvokeMember("MyProp", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.SetProperty, Nothing, obj, New [Object]() {0})
Catch e As TargetInvocationException
' If the property assignment failed for some unexpected
' reason, rethrow the TargetInvocationException.
If Not e.InnerException.GetType() Is GetType(ArgumentOutOfRangeException) Then
Throw
End If
Console.WriteLine("An invalid value was assigned to MyProp.")
End Try
t.InvokeMember("MyProp", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.SetProperty, Nothing, obj, New [Object]() {2})
v = CType(t.InvokeMember("MyProp", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.GetProperty, Nothing, obj, Nothing), Int32)
Console.WriteLine("MyProp: {0}", v)
End Sub
End Class
Commenti
Nota
Non è possibile InvokeMember utilizzare per richiamare un metodo generico.You cannot use InvokeMember to invoke a generic method.
I flag BindingFlags di filtro seguenti possono essere usati per definire i membri da includere nella ricerca:The following BindingFlags filter flags can be used to define which members to include in the search:
Consente
BindingFlags.Public
di specificare di includere i membri pubblici nella ricerca.SpecifyBindingFlags.Public
to include public members in the search.Specificare
BindingFlags.NonPublic
per includere i membri non pubblici (ovvero membri privati e protetti) nella ricerca.SpecifyBindingFlags.NonPublic
to include non-public members (that is, private and protected members) in the search.Specificare
BindingFlags.FlattenHierarchy
per includere i membri statici nella gerarchia.SpecifyBindingFlags.FlattenHierarchy
to include static members up the hierarchy.
I flag BindingFlags di modifica seguenti possono essere utilizzati per modificare il funzionamento della ricerca:The following BindingFlags modifier flags can be used to change how the search works:
BindingFlags.IgnoreCase
per ignorare la distinzione traname
maiuscole e minuscole.BindingFlags.IgnoreCase
to ignore the case ofname
.BindingFlags.DeclaredOnly
per cercare solo i membri dichiarati Typein, non i membri che sono stati semplicemente ereditati.BindingFlags.DeclaredOnly
to search only the members declared on the Type, not members that were simply inherited.
I flag BindingFlags di chiamata seguenti possono essere usati per indicare l'azione da eseguire con il membro:The following BindingFlags invocation flags can be used to denote what action to take with the member:
CreateInstance
per richiamare un costruttore.CreateInstance
to invoke a constructor.name
viene ignorato.name
is ignored. Non valido con altri flag di chiamata.Not valid with other invocation flags.InvokeMethod
per richiamare un metodo, ma non un costruttore o un inizializzatore di tipo.InvokeMethod
to invoke a method, but not a constructor or a type initializer. Non valido conSetField
oSetProperty
.Not valid withSetField
orSetProperty
. SeInvokeMethod
viene specificato da soloBindingFlags.Instance
,BindingFlags.Public
, eBindingFlags.Static
vengono inclusi automaticamente.IfInvokeMethod
is specified by itself,BindingFlags.Public
,BindingFlags.Instance
, andBindingFlags.Static
are automatically included.GetField
per ottenere il valore di un campo.GetField
to get the value of a field. Non valido conSetField
.Not valid withSetField
.SetField
per impostare il valore di un campo.SetField
to set the value of a field. Non valido conGetField
.Not valid withGetField
.GetProperty
per ottenere una proprietà.GetProperty
to get a property. Non valido conSetProperty
.Not valid withSetProperty
.SetProperty
per impostare una proprietà.SetProperty
to set a property. Non valido conGetProperty
.Not valid withGetProperty
.
Per altre informazioni, vedere System.Reflection.BindingFlags.See System.Reflection.BindingFlags for more information.
Viene richiamato un metodo se si verificano entrambe le condizioni seguenti:A method will be invoked if both of the following conditions are true:
Il numero di parametri nella dichiarazione di metodo è uguale al numero di argomenti nella
args
matrice (a meno che non siano definiti argomenti predefiniti per il membro eBindingFlags.OptionalParamBinding
che sia specificato).The number of parameters in the method declaration equals the number of arguments in theargs
array (unless default arguments are defined on the member andBindingFlags.OptionalParamBinding
is specified).Il tipo di ogni argomento può essere convertito dal gestore di associazione al tipo del parametro.The type of each argument can be converted by the binder to the type of the parameter.
Il Binder troverà tutti i metodi corrispondenti.The binder will find all of the matching methods. Questi metodi si basano sul tipo di binding richiesto (BindingFlags valori InvokeMethod
, GetProperty
e così via).These methods are found based upon the type of binding requested (BindingFlags values InvokeMethod
, GetProperty
, and so on). Il set di metodi viene filtrato in base al nome, al numero di argomenti e a un set di modificatori di ricerca definiti nel gestore di associazione.The set of methods is filtered by the name, number of arguments, and a set of search modifiers defined in the binder.
Una volta selezionato, il metodo viene richiamato.After the method is selected, it is invoked. L'accessibilità viene controllata a questo punto.Accessibility is checked at that point. La ricerca può controllare il set di metodi in base all'attributo di accessibilità associato al metodo.The search may control which set of methods are searched based upon the accessibility attribute associated with the method. Il Binder.BindToMethod metodoBinder della classe è responsabile della selezione del metodo da richiamare.The Binder.BindToMethod method of the Binder class is responsible for selecting the method to be invoked. Il binder predefinito seleziona la corrispondenza più specifica.The default binder selects the most specific match.
Le restrizioni di accesso vengono ignorate per il codice completamente attendibile; ovvero, i costruttori privati, i metodi, i campi e le proprietà possono essere accessibili e richiamati tramite System.Reflection ogni volta che il codice è completamente attendibile.Access restrictions are ignored for fully trusted code; that is, private constructors, methods, fields, and properties can be accessed and invoked through System.Reflection whenever the code is fully trusted.
È possibile utilizzare Type.InvokeMember
per impostare un campo su un valore specifico specificando BindingFlags.SetField.You can use Type.InvokeMember
to set a field to a particular value by specifying BindingFlags.SetField. Se, ad esempio, si vuole impostare un campo di istanza pubblica denominato F nella classe C e f è un String
, è possibile usare codice come il seguente:For example, if you want to set a public instance field named F on class C, and F is a String
, you can use code such as:
typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {"strings new value"});
Se F è un String[]
, è possibile usare codice come il seguente:If F is a String[]
, you can use code such as:
typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {new String[]{"a","z","c","d"}});
che consente di inizializzare il campo F nella nuova matrice.which will initialize the field F to this new array. È anche possibile usare Type.InvokeMember
per impostare una posizione in una matrice fornendo l'indice del valore e quindi il valore successivo usando un codice simile al seguente:You can also use Type.InvokeMember
to set a position in an array by supplying the index of the value and then the next value by using code such as the following:
typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {1, "b"});
In questo modo verrà modificata la stringa "z" nella matrice che F viene mantenuta nella stringa "b".This will change string "z" in the array that F holds to string "b".
Quando si richiama un IDispatch
membro, è possibile specificare il DISPID anziché il nome del membro, usando il formato stringa "[DISPID = # #]".When you invoke an IDispatch
member, you can specify the DispID instead of the member name, using the string format "[DispID=##]". Se, ad esempio, il DispID di MyComMethod è 3, è possibile specificare la stringa "[DispID = 3]" anziché "MyComMethod".For example, if the DispID of MyComMethod is 3, you can specify the string "[DispID=3]" instead of "MyComMethod". La chiamata di un membro tramite DispID è più veloce rispetto alla ricerca del membro in base al nome.Invoking a member by DispID is faster than looking up the member by name. Negli scenari di aggregazione complessi, il DispID è talvolta l'unico modo per richiamare il membro desiderato.In complex aggregation scenarios, the DispID is sometimes the only way to invoke the desired member.
Nota
A partire da .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a membri non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei membri non pubblici è limitato al set di concessioni del chiamante o a un subset loro.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. Vedere considerazioni sulla sicurezza per la reflection.(See Security Considerations for Reflection.)
Per usare questa funzionalità, l'applicazione deve essere destinata a .NET Framework 3.5.NET Framework 3.5 o versione successiva.To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.
Sicurezza
ReflectionPermission
per accedere ai membri non pubblici indipendentemente dal set di concessioni.for accessing non-public members regardless of their grant set. Enumerazione associata:MemberAccessAssociated enumeration: MemberAccess
SecurityPermission
per chiamare codice non gestito.to call unmanaged code. Enumerazione associata:UnmanagedCodeAssociated enumeration: UnmanagedCode
Vedi anche
InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo)
Chiama il membro specificato, usando i vincoli di binding specificati e associando l'elenco di argomenti specificati e le impostazioni cultura.Invokes the specified member, using the specified binding constraints and matching the specified argument list and culture.
public:
virtual System::Object ^ InvokeMember(System::String ^ name, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, System::Object ^ target, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture);
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Globalization.CultureInfo culture);
abstract member InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] * System.Globalization.CultureInfo -> obj
override this.InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] * System.Globalization.CultureInfo -> obj
Parametri
- name
- String
Stringa che contiene il nome del costruttore, del metodo, della proprietà o del membro del campo da richiamare.The string containing the name of the constructor, method, property, or field member to invoke.
In alternativa-or- Stringa vuota ("") per richiamare il membro predefinito.An empty string ("") to invoke the default member.
-oppure--or-
Per i membri IDispatch
, stringa che rappresenta DispID, ad esempio "[DispID=3]".For IDispatch
members, a string representing the DispID, for example "[DispID=3]".
- invokeAttr
- 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. L'accesso può essere uno dei BindingFlags
, ad esempio Public
, NonPublic
, Private
, InvokeMethod
, GetField
e così via.The access can be one of the BindingFlags
such as Public
, NonPublic
, Private
, InvokeMethod
, GetField
, and so on. Il tipo di ricerca non deve essere specificato.The type of lookup need not be specified. Se il tipo di ricerca viene omesso, vengono usati BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.Static
.If the type of lookup is omitted, BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.Static
are used.
- 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.
In alternativa-or-
Riferimento Null (Nothing
in Visual Basic) per l'uso di DefaultBinder.A null reference (Nothing
in Visual Basic), to use the DefaultBinder. Si noti che potrebbe essere necessario definire in modo esplicito un oggetto Binder per richiamare correttamente overload di metodo con argomenti variabili.Note that explicitly defining a Binder object may be required for successfully invoking method overloads with variable arguments.
- target
- Object
Oggetto su cui richiamare il membro specificato.The object on which to invoke the specified member.
- args
- Object[]
Matrice che contiene gli argomenti da passare al membro da richiamare.An array containing the arguments to pass to the member to invoke.
- culture
- CultureInfo
Oggetto che rappresenta le impostazioni locali di globalizzazione da usare, che possono essere necessarie per conversioni specifiche delle impostazioni locali, ad esempio la conversione di un oggetto String numerico in Double.The object representing the globalization locale to use, which may be necessary for locale-specific conversions, such as converting a numeric String to a Double.
-oppure--or-
Riferimento Null (Nothing
in Visual Basic) per l'uso dell'oggetto CultureInfo del thread corrente.A null reference (Nothing
in Visual Basic) to use the current thread's CultureInfo.
Restituisce
Oggetto che rappresenta il valore restituito di un membro richiamato.An object representing the return value of the invoked member.
Implementazioni
Eccezioni
invokeAttr
non contiene CreateInstance
e name
è null
.invokeAttr
does not contain CreateInstance
and name
is null
.
invokeAttr
non è un attributo valido di BindingFlags.invokeAttr
is not a valid BindingFlags attribute.
In alternativa-or-
invokeAttr
non contiene uno dei flag di binding seguenti: InvokeMethod
, CreateInstance
, GetField
, SetField
, GetProperty
o SetProperty
.invokeAttr
does not contain one of the following binding flags: InvokeMethod
, CreateInstance
, GetField
, SetField
, GetProperty
, or SetProperty
.
In alternativa-or-
invokeAttr
contiene CreateInstance
in combinazione con InvokeMethod
, GetField
, SetField
, GetProperty
o SetProperty
.invokeAttr
contains CreateInstance
combined with InvokeMethod
, GetField
, SetField
, GetProperty
, or SetProperty
.
In alternativa-or-
invokeAttr
contiene sia GetField
che SetField
.invokeAttr
contains both GetField
and SetField
.
-oppure--or-
invokeAttr
contiene sia GetProperty
che SetProperty
.invokeAttr
contains both GetProperty
and SetProperty
.
In alternativa-or-
invokeAttr
contiene InvokeMethod
in combinazione con SetField
o SetProperty
.invokeAttr
contains InvokeMethod
combined with SetField
or SetProperty
.
In alternativa-or-
invokeAttr
contiene SetField
e args
include più elementi.invokeAttr
contains SetField
and args
has more than one element.
-oppure--or-
Questo metodo è stato chiamato su un oggetto COM e uno dei flag di binding seguenti non è stato passato: BindingFlags.InvokeMethod
, BindingFlags.GetProperty
, BindingFlags.SetProperty
, BindingFlags.PutDispProperty
o BindingFlags.PutRefDispProperty
.This method is called on a COM object and one of the following binding flags was not passed in: BindingFlags.InvokeMethod
, BindingFlags.GetProperty
, BindingFlags.SetProperty
, BindingFlags.PutDispProperty
, or BindingFlags.PutRefDispProperty
.
-oppure--or-
Una delle matrici di parametri denominati contiene una stringa null
.One of the named parameter arrays contains a string that is null
.
Il membro specificato è un inizializzatore di classi.The specified member is a class initializer.
Non è possibile trovare il campo o la proprietà.The field or property cannot be found.
Non è possibile trovare metodi corrispondenti agli argomenti in args
.No method can be found that matches the arguments in args
.
-oppure--or-
L'oggetto Type corrente rappresenta un tipo che contiene parametri di tipo open, ovvero ContainsGenericParameters restituisce true
.The current Type object represents a type that contains open type parameters, that is, ContainsGenericParameters returns true
.
Non è possibile richiamare il metodo specificato su target
.The specified member cannot be invoked on target
.
Più di un metodo corrisponde ai criteri di binding.More than one method matches the binding criteria.
Il metodo rappresentato da name
include uno o più parametri di tipo generico non specificati.The method represented by name
has one or more unspecified generic type parameters. In altri termini, la proprietà ContainsGenericParameters del metodo restituisce true
.That is, the method's ContainsGenericParameters property returns true
.
Commenti
Sebbene il Binder CultureInfo predefinito non elabori (il culture
parametro), è possibile usare la classe astratta System.Reflection.Binder per scrivere un gestore di associazione personalizzato che esegue culture
l'elaborazione.Although the default binder does not process CultureInfo (the culture
parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process culture
.
Nota
Non è possibile InvokeMember utilizzare per richiamare un metodo generico.You cannot use InvokeMember to invoke a generic method.
I flag BindingFlags di filtro seguenti possono essere usati per definire i membri da includere nella ricerca:The following BindingFlags filter flags can be used to define which members to include in the search:
Consente
BindingFlags.Public
di specificare di includere i membri pubblici nella ricerca.SpecifyBindingFlags.Public
to include public members in the search.Specificare
BindingFlags.NonPublic
per includere i membri non pubblici (ovvero i membri privati, interni e protetti) nella ricerca.SpecifyBindingFlags.NonPublic
to include non-public members (that is, private, internal, and protected members) in the search.Specificare
BindingFlags.FlattenHierarchy
per includere i membri statici nella gerarchia.SpecifyBindingFlags.FlattenHierarchy
to include static members up the hierarchy.
I flag BindingFlags di modifica seguenti possono essere utilizzati per modificare il funzionamento della ricerca:The following BindingFlags modifier flags can be used to change how the search works:
BindingFlags.IgnoreCase
per ignorare la distinzione traname
maiuscole e minuscole.BindingFlags.IgnoreCase
to ignore the case ofname
.BindingFlags.DeclaredOnly
per cercare solo i membri dichiarati Typein, non i membri che sono stati semplicemente ereditati.BindingFlags.DeclaredOnly
to search only the members declared on the Type, not members that were simply inherited.
I flag BindingFlags di chiamata seguenti possono essere usati per indicare l'azione da eseguire con il membro:The following BindingFlags invocation flags can be used to denote what action to take with the member:
CreateInstance
per richiamare un costruttore.CreateInstance
to invoke a constructor.name
viene ignorato.name
is ignored. Non valido con altri flag di chiamata.Not valid with other invocation flags.InvokeMethod
per richiamare un metodo, ma non un costruttore o un inizializzatore di tipo.InvokeMethod
to invoke a method, but not a constructor or a type initializer. Non valido conSetField
oSetProperty
.Not valid withSetField
orSetProperty
. SeInvokeMethod
viene specificato da soloBindingFlags.Instance
,BindingFlags.Public
, eBindingFlags.Static
vengono inclusi automaticamente.IfInvokeMethod
is specified by itself,BindingFlags.Public
,BindingFlags.Instance
, andBindingFlags.Static
are automatically included.GetField
per ottenere il valore di un campo.GetField
to get the value of a field. Non valido conSetField
.Not valid withSetField
.SetField
per impostare il valore di un campo.SetField
to set the value of a field. Non valido conGetField
.Not valid withGetField
.GetProperty
per ottenere una proprietà.GetProperty
to get a property. Non valido conSetProperty
.Not valid withSetProperty
.SetProperty
per impostare una proprietà.SetProperty
to set a property. Non valido conGetProperty
.Not valid withGetProperty
.
Per altre informazioni, vedere System.Reflection.BindingFlags.See System.Reflection.BindingFlags for more information.
Viene richiamato un metodo se si verificano entrambe le condizioni seguenti:A method will be invoked if both of the following conditions are true:
Il numero di parametri nella dichiarazione di metodo è uguale al numero di argomenti nella
args
matrice (a meno che non siano definiti argomenti predefiniti per il membro eBindingFlags.OptionalParamBinding
che sia specificato).The number of parameters in the method declaration equals the number of arguments in theargs
array (unless default arguments are defined on the member andBindingFlags.OptionalParamBinding
is specified).Il tipo di ogni argomento può essere convertito dal gestore di associazione al tipo del parametro.The type of each argument can be converted by the binder to the type of the parameter.
Il Binder troverà tutti i metodi corrispondenti.The binder will find all of the matching methods. Questi metodi si basano sul tipo di binding richiesto (BindingFlags valori InvokeMethod
, GetProperty
e così via).These methods are found based upon the type of binding requested (BindingFlags values InvokeMethod
, GetProperty
, and so on). Il set di metodi viene filtrato in base al nome, al numero di argomenti e a un set di modificatori di ricerca definiti nel gestore di associazione.The set of methods is filtered by the name, number of arguments, and a set of search modifiers defined in the binder.
Una volta selezionato, il metodo viene richiamato.After the method is selected, it is invoked. L'accessibilità viene controllata a questo punto.Accessibility is checked at that point. La ricerca può controllare il set di metodi in base all'attributo di accessibilità associato al metodo.The search may control which set of methods are searched based upon the accessibility attribute associated with the method. Il Binder.BindToMethod metodoBinder della classe è responsabile della selezione del metodo da richiamare.The Binder.BindToMethod method of the Binder class is responsible for selecting the method to be invoked. Il binder predefinito seleziona la corrispondenza più specifica.The default binder selects the most specific match.
Le restrizioni di accesso vengono ignorate per il codice completamente attendibile; ovvero, i costruttori privati, i metodi, i campi e le proprietà possono essere accessibili e richiamati tramite reflection ogni volta che il codice è completamente attendibile.Access restrictions are ignored for fully trusted code; that is, private constructors, methods, fields, and properties can be accessed and invoked through Reflection whenever the code is fully trusted.
È possibile utilizzare Type.InvokeMember
per impostare un campo su un valore specifico specificando BindingFlags.SetField.You can use Type.InvokeMember
to set a field to a particular value by specifying BindingFlags.SetField. Se, ad esempio, si vuole impostare un campo di istanza pubblica denominato F nella classe C e f è un String
, è possibile usare codice come il seguente:For example, if you want to set a public instance field named F on class C, and F is a String
you can use code such as:
typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {"strings new value"}, null);
Se F è un String[]
, è possibile usare codice come il seguente:If F is a String[]
, you can use code such as:
typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {new String[]{"a","z","c","d"}}, null);
che consente di inizializzare il campo F nella nuova matrice.which will initialize the field F to this new array. È anche possibile usare Type.InvokeMember
per impostare una posizione in una matrice fornendo l'indice del valore e quindi il valore successivo usando un codice simile al seguente:You can also use Type.InvokeMember
to set a position in an array by supplying the index of the value and then the next value by using code such as the following:
typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {1, "b"}, null);
In questo modo verrà modificata la stringa "z" nella matrice che F viene mantenuta nella stringa "b".This will change string "z" in the array that F holds to string "b".
Quando si richiama un IDispatch
membro è possibile specificare il DISPID anziché il nome del membro, usando il formato stringa "[DISPID = # #]".When you invoke an IDispatch
member you can specify the DispID instead of the member name, using the string format "[DispID=##]". Se, ad esempio, il DispID di MyComMethod è 3, è possibile specificare la stringa "[DispID = 3]" anziché "MyComMethod".For example, if the DispID of MyComMethod is 3, you can specify the string "[DispID=3]" instead of "MyComMethod". La chiamata di un membro tramite DispID è più veloce rispetto alla ricerca del membro in base al nome.Invoking a member by DispID is faster than looking up the member by name. Negli scenari di aggregazione complessi, il DispID è talvolta l'unico modo per richiamare il membro desiderato.In complex aggregation scenarios, the DispID is sometimes the only way to invoke the desired member.
Nota
A partire da .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a membri non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei membri non pubblici è limitato al set di concessioni del chiamante o a un subset loro.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. Vedere considerazioni sulla sicurezza per la reflection.(See Security Considerations for Reflection.)
Per usare questa funzionalità, l'applicazione deve essere destinata a .NET Framework 3.5.NET Framework 3.5 o versione successiva.To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.
Sicurezza
ReflectionPermission
per accedere ai membri non pubblici indipendentemente dal set di concessioni.for accessing non-public members regardless of their grant set. Enumerazione associata:MemberAccessAssociated enumeration: MemberAccess
SecurityPermission
per chiamare codice non gestito.to call unmanaged code. Enumerazione associata:UnmanagedCodeAssociated enumeration: UnmanagedCode