Type.InvokeMember, méthode (String, BindingFlags, Binder, Object, Object[])
Assembly : mscorlib (dans mscorlib.dll)
public Object InvokeMember ( string name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args )
public final Object InvokeMember ( String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args )
public final function InvokeMember ( name : String, invokeAttr : BindingFlags, binder : Binder, target : Object, args : Object[] ) : Object
Paramètres
- name
String contenant le nom du membre de constructeur, de méthode, de propriété ou de champ à appeler.
– ou –
Une chaîne vide ("") pour appeler le membre par défaut.
– ou –
Pour les membres IDispatch, chaîne représentant le DispID, par exemple "[DispID=3]".
- invokeAttr
Masque de bits constitué d'un ou de plusieurs BindingFlags spécifiant le mode d'exécution de la recherche. L'accès peut être fourni par l'un des BindingFlags, par exemple Public, NonPublic, Private, InvokeMethod, GetField, etc. Il n'est pas nécessaire de spécifier le type de recherche. Si le type de recherche est omis, BindingFlags.Public | BindingFlags.Instance s'applique.
- binder
Objet Binder qui définit un ensemble de propriétés et permet la liaison, ce qui peut impliquer la sélection d'une méthode surchargée, la contrainte de types d'arguments et l'appel d'un membre par la réflexion.
– ou –
référence Null (Nothing en Visual Basic), pour utiliser DefaultBinder.
- target
Object sur lequel le membre spécifié doit être appelé.
- args
Tableau contenant les arguments à passer au membre à appeler.
Valeur de retour
Object représentant la valeur de retour du membre appelé.| Type d'exception | Condition |
|---|---|
| invokeAttr contient CreateInstance et typeName est référence Null (Nothing en Visual Basic). | |
| args est multidimensionnel. – ou – invokeAttr n'est pas un attribut BindingFlags valide – ou – invokeAttr contient CreateInstance combiné avec InvokeMethod, GetField, SetField, GetProperty ou SetProperty. – ou – invokeAttr contient à la fois GetField et SetField. – ou – invokeAttr contient à la fois GetProperty et SetProperty. – ou – invokeAttr contient InvokeMethod combiné avec SetField ou SetProperty. – ou – invokeAttr contient SetField et args compte plusieurs éléments. – ou – Cette méthode est appelée sur un objet COM et l'un des indicateurs de liaison suivants n'a pas été passé : BindingFlags.InvokeMethod, BindingFlags.GetProperty, BindingFlags.SetProperty, BindingFlags.PutDispProperty ou BindingFlags.PutRefDispProperty. – ou – L'un des tableaux de paramètres nommés contient une chaîne qui est référence Null (Nothing en Visual Basic). | |
| Le membre spécifié est un initialiseur de classe. | |
| Impossible de trouver le champ ou la propriété. | |
| La méthode est introuvable. – ou – L'objet Type actuel représente un type qui contient des paramètres de type ouverts, c'est-à-dire que ContainsGenericParameters retourne la valeur true. | |
| Le membre spécifié ne peut pas être appelé sur target. | |
| Plusieurs méthodes correspondent aux critères de liaison. | |
| Le .NET Compact Framework ne prend pas en charge actuellement cette propriété. |
Les indicateurs de filtre BindingFlags suivants peuvent être utilisés pour définir les membres à inclure dans la recherche :
-
Vous devez spécifier soit BindingFlags.Instance, soit BindingFlags.Static pour obtenir un retour.
-
Spécifiez BindingFlags.Public pour inclure les membres publics dans la recherche.
-
Spécifiez BindingFlags.NonPublic pour inclure les membres non publics (c'est-à-dire les membres privés et protégés) dans la recherche.
-
Spécifiez BindingFlags.FlattenHierarchy pour inclure les membres statiques en haut de la hiérarchie.
Les indicateurs de modificateur BindingFlags suivants peuvent être utilisés pour modifier le fonctionnement de la recherche :
-
BindingFlags.IgnoreCase pour ignorer la casse de name.
-
BindingFlags.DeclaredOnly pour limiter la recherche aux membres déclarés dans Type et exclure ceux qui ont été simplement hérités.
Les indicateurs d'appel BindingFlags suivants peuvent être utilisés pour désigner l'action à effectuer sur le membre :
-
CreateInstance pour appeler un constructeur. name est ignoré. Non valide avec d'autres indicateurs d'appel.
-
InvokeMethod pour appeler une méthode, mais pas un constructeur ni un initialiseur de type. Non valide avec SetField ou SetProperty.
-
GetField pour obtenir la valeur d'un champ. Non valide avec SetField.
-
SetField pour définir la valeur d'un champ. Non valide avec GetField.
-
GetProperty pour obtenir une propriété. Non valide avec SetProperty.
-
SetProperty pour définir une propriété. Non valide avec GetProperty.
Pour plus d'informations, consultez System.Reflection.BindingFlags.
Une méthode est appelée si les conditions suivantes sont vérifiées :
-
Le nombre de paramètres de la déclaration de méthode est égal au nombre d'arguments du tableau args (à moins que le membre ne possède des arguments définis par défaut) et
-
Le type de chaque argument peut être converti par le binder pour correspondre au type du paramètre.
Le binder va trouver toutes les méthodes correspondantes. Ces méthodes sont trouvées en fonction du type de liaison demandé (valeurs BindingFlags, InvokeMethod, GetProperty, etc.). L'ensemble des méthodes est filtré selon leur nom, leur nombre d'arguments et un ensemble de modificateurs de recherche définis dans le binder.
Une fois sélectionnée, la méthode est appelée. L'accessibilité est vérifiée à ce stade. La recherche peut contrôler quel ensemble de méthodes est analysé en fonction de l'attribut d'accessibilité associé à chaque méthode. La méthode Binder.BindToMethod de la classe Binder est chargée de sélectionner la méthode à appeler. Le binder par défaut sélectionne la correspondance la plus spécifique.
Les restrictions d'accès sont ignorées pour le code d'un niveau de confiance suffisant ; autrement dit, il est possible d'accéder et de faire appel à des constructeurs, méthodes, champs et propriétés privés via System.Reflection dès lors que le code est d'un niveau de confiance suffisant.
Vous pouvez utiliser Type.InvokeMember pour affecter une valeur spécifique à un champ en spécifiant BindingFlags.SetField. Par exemple, si vous voulez définir un champ d'instance public nommé F sur la classe C, et si F est String, vous pouvez utiliser le code suivant :
typeof(C).InvokeMember("F", BindingFlags.SetField, null, C, new Object{"strings new value"});
Si F est String[], vous pouvez utiliser le code suivant :
typeof(C).InvokeMember("F", BindingFlags.SetField, null, C, new Object{new String[]{"a","z","c","d"});
ce qui initialisera le champ F à ce nouveau tableau. De plus, vous pouvez utiliser Type.InvokeMember pour définir une position dans un tableau en fournissant l'index de la valeur puis la valeur suivante, à l'aide du code suivant :
typeof(C).InvokeMember("F", BindingFlags.SetField, null, C, new Object{1, "b"});
La chaîne "z" du tableau que F contient est remplacée par la chaîne "b".
Lorsque vous appelez un membre IDispatch, vous pouvez spécifier le DispID à la place du nom de membre à l'aide du format de chaîne "[DispID=##]". Par exemple, si le DispID de MyComMethod est 3, vous pouvez spécifier la chaîne "[DispID=3]" à la place de "MyComMethod". Il est plus rapide d'appeler un membre par DispID que de le rechercher par son nom. Dans des scénarios d'agrégation complexes, le DispID représente parfois la seule façon d'appeler le membre souhaité.
L'exemple suivant utilise InvokeMember pour accéder aux membres d'un type.
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); } }
import System.*;
import System.Reflection.*;
// This sample class has a field, constructor, method, and property.
class MyType
{
private int myField;
public MyType(
/**@ref
*/ int x)
{
x *= 5;
} //MyType
public String ToString()
{
return System.Convert.ToString(myField);
} //ToString
/** @property
*/
public int get_MyProp()
{
return myField;
} //get_MyProp
/** @property
*/
public void set_MyProp(int value)
{
if (value < 1) {
throw new ArgumentOutOfRangeException("value",
(Int32)value, "value must be > 0");
}
myField = value;
} //set_MyProp
} //MyType
class MyApp
{
public static void main(String[] args)
throws System.Reflection.TargetInvocationException
{
Type t = MyType.class.ToType();
// Create an instance of a type.
Object args1[] = new Object[] { (Int32)8 };
Console.WriteLine("The value of x before the constructor"
+ " is called is {0}.", args1[0]);
Object obj = t.InvokeMember(null, BindingFlags.DeclaredOnly
| BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.CreateInstance,
null, null, args1);
Console.WriteLine("Type: " + obj.GetType().ToString());
Console.WriteLine("The value of x after the constructor "
+ "returns is {0}.", args1[0]);
// Read and write to a field.
t.InvokeMember("myField", BindingFlags.DeclaredOnly
| BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.SetField, null,
obj, new Object[] { (Int32)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[] { (Int32)0 });
}
catch (TargetInvocationException e) {
// If the property assignment failed for some unexpected
// reason, rethrow the TargetInvocationException.
if (!(e.get_InnerException().GetType().Equals
(ArgumentOutOfRangeException.class.ToType()))) {
throw e;
}
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[] { (Int32)2 });
v = (Int32)t.InvokeMember("MyProp", BindingFlags.DeclaredOnly
| BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.GetProperty, null,
obj, null);
Console.WriteLine("MyProp: " + v);
} //main
} //MyApp
- ReflectionPermission pour réfléchir les membres non publics. Énumération associée : ReflectionPermissionFlag.MemberAccess
- SecurityPermission pour appeler un code non managé. Énumération associée : SecurityPermissionFlag.UnmanagedCode
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition
Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.