BindingFlags Énumération

Définition

Spécifie des indicateurs qui contrôlent la liaison et la manière dont la recherche de membres et de types est exécutée par réflexion.

Cette énumération prend en charge une combinaison au niveau du bit de ses valeurs membres.

public enum class BindingFlags
[System.Flags]
public enum BindingFlags
[System.Flags]
[System.Serializable]
public enum BindingFlags
[System.Flags]
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum BindingFlags
[<System.Flags>]
type BindingFlags = 
[<System.Flags>]
[<System.Serializable>]
type BindingFlags = 
[<System.Flags>]
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type BindingFlags = 
Public Enum BindingFlags
Héritage
BindingFlags
Attributs

Champs

CreateInstance 512

Spécifie que la réflexion doit créer une instance du type spécifié. Appelle le constructeur qui correspond aux arguments donnés. Le nom de membre fourni est ignoré. Si le type de recherche n’est pas spécifié, (Instance | Public) s’applique. Il n’est pas possible d’appeler un initialiseur de type.

Cet indicateur est passé à une méthode InvokeMember pour appeler un constructeur.

DeclaredOnly 2

Spécifie que seuls les membres déclarés au niveau de la hiérarchie du type fourni doivent être pris en compte. Les membres hérités ne sont pas pris en compte.

Default 0

Spécifie qu’aucun indicateur de liaison n’est défini.

DoNotWrapExceptions 33554432
ExactBinding 65536

Spécifie que les types des arguments fournis doivent correspondre exactement aux types des paramètres formels correspondants. La réflexion lève une exception si l’appelant fournit un objet Binder non null, car cela implique que l’appelant fournisse des implémentations de BindToXXX qui sélectionnent la méthode appropriée. Le binder par défaut ignore cet indicateur, tandis que les binders personnalisés peuvent implémenter la sémantique de cet indicateur.

FlattenHierarchy 64

Spécifie que les membres statiques publics et protégés en haut de la hiérarchie doivent être retournés. Les membres statiques privés des classes héritées ne sont pas retournés. Les membres statiques comprennent les champs, les méthodes, les propriétés et les événements. Les types imbriqués ne sont pas retournés.

GetField 1024

Spécifie que la valeur du champ spécifié doit être retournée.

Cet indicateur est passé à une méthode InvokeMember pour obtenir la valeur d’un champ.

GetProperty 4096

Spécifie que la valeur de la propriété spécifiée doit être retournée.

Cet indicateur est passé à une méthode InvokeMember pour appeler la méthode getter d’une propriété.

IgnoreCase 1

Spécifie que la casse du nom de membre ne doit pas être prise en compte lors de la liaison.

IgnoreReturn 16777216

Utilisé dans COM Interop pour spécifier que la valeur de retour du membre peut être ignorée.

Instance 4

Spécifie que les membres d’instance doivent être inclus dans la recherche.

InvokeMethod 256

Spécifie qu’une méthode doit être appelée. Il ne doit pas s’agir d’un constructeur ou d’un initialiseur de type.

Cet indicateur est passé à une méthode InvokeMember pour appeler une méthode.

NonPublic 32

Spécifie que les membres non publics doivent être inclus dans la recherche.

OptionalParamBinding 262144

Retourne l’ensemble de membres dont le nombre de paramètres correspond au nombre d’arguments fournis. Cet indicateur de liaison est utilisé pour les méthodes avec des paramètres qui ont des valeurs par défaut et pour les méthodes avec des arguments de variable (varargs). Cet indicateur doit être utilisé seulement avec InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]).

Les paramètres avec des valeurs par défaut sont utilisés uniquement dans les appels où les arguments de fin sont omis. Ils doivent être les derniers arguments.

Public 16

Spécifie que les membres publics doivent être inclus dans la recherche.

PutDispProperty 16384

Spécifie que le membre PROPPUT sur un objet COM doit être appelé. PROPPUT spécifie une fonction de définition de propriété qui utilise une valeur. Utilisez PutDispProperty si une propriété a à la fois PROPPUT et PROPPUTREF, et que vous devez distinguer celle qui est appelée.

PutRefDispProperty 32768

Spécifie que le membre PROPPUTREF sur un objet COM doit être appelé. PROPPUTREF spécifie une fonction de définition de propriété qui utilise une référence au lieu d’une valeur. Utilisez PutRefDispProperty si une propriété a à la fois PROPPUT et PROPPUTREF, et que vous devez distinguer celle qui est appelée.

SetField 2048

Spécifie que la valeur du champ spécifié doit être définie.

Cet indicateur est passé à une méthode InvokeMember pour définir la valeur d’un champ.

SetProperty 8192

Spécifie que la valeur de la propriété spécifiée doit être définie. Pour les propriétés COM, la spécification de cet indicateur de liaison est équivalente à la spécification de PutDispProperty et de PutRefDispProperty.

Cet indicateur est passé à une méthode InvokeMember pour appeler la méthode setter d’une propriété.

Static 8

Spécifie que les membres statiques doivent être inclus dans la recherche.

SuppressChangeType 131072

Non implémenté.

Exemples

L’exemple suivant illustre la plupart des indicateurs de liaison.

using namespace System;
using namespace System::Collections;
using namespace System::Reflection;
using namespace System::IO;

//namespace BindingFlagsSnippet {
public ref class TestClass
{
public:
   String^ Name;

private:
   array<Object^>^ values;
   int methodCalled;

public:

   property Object^ Item [int]
   {
      Object^ get( int index )
      {
         return values[ index ];
      }

      void set( int index, Object^ value )
      {
         values[ index ] = value;
      }
   }

   property Object^ Value
   {
      Object^ get()
      {
         return "the value";
      }
   }

   TestClass() 
   {
      Name = "initialName";
      values = gcnew array<Object^> {(int^)0,1,2,3,4,5,6,7,8,9};
      methodCalled = 0;
   }
   
   TestClass(String^ initName)
   {
      Name = initName;
      values = gcnew array<Object^> {(int^)0,1,2,3,4,5,6,7,8,9};
      methodCalled = 0;
   }

   static void SayHello()
   {
      Console::WriteLine( "Hello" );
   }

   void AddUp()
   {
      methodCalled++;
      Console::WriteLine( "AddUp Called {0} times", methodCalled );
   }

   static double ComputeSum( double d1, double d2 )
   {
      return d1 + d2;
   }

   static void PrintName( String^ firstName, String^ lastName )
   {
      Console::WriteLine( "{0},{1}", lastName, firstName );
   }

   void PrintTime()
   {
      Console::WriteLine( DateTime::Now );
   }

   void Swap( interior_ptr<int> a, interior_ptr<int> b )
   {
      int x =  *a;
       *a =  *b;
       *b = x;
   }
};


[DefaultMemberAttribute("PrintTime")]
public ref class TestClass2
{
public:
   void PrintTime()
   {
      Console::WriteLine( DateTime::Now );
   }

};

public ref class Base
{
private:
    static int BaseOnlyPrivate = 0;
protected:
    static int BaseOnly = 0;
};

public ref class Derived : Base
{
public:
    static int DerivedOnly = 0;
};

public ref class MostDerived : Derived {};

void main()
{
   array<Object^>^ noArguments;

   // BindingFlags::InvokeMethod
   // Call a static method.
   Type^ t = TestClass::typeid;
   Console::WriteLine();
   Console::WriteLine( "Invoking a static method." );
   Console::WriteLine( "-------------------------" );
   t->InvokeMember( "SayHello", BindingFlags::InvokeMethod | BindingFlags::Public | BindingFlags::Static, 
         nullptr, nullptr, noArguments );

   // BindingFlags::InvokeMethod
   // Call an instance method.
   TestClass^ c = gcnew TestClass;
   Console::WriteLine();
   Console::WriteLine( "Invoking an instance method." );
   Console::WriteLine( "----------------------------" );
   c->GetType()->InvokeMember( "AddUp", BindingFlags::InvokeMethod, nullptr, c, noArguments );
   c->GetType()->InvokeMember( "AddUp", BindingFlags::InvokeMethod, nullptr, c, noArguments );

   // BindingFlags::InvokeMethod
   // Call a method with parameters.
   array<Object^>^args = {100.09,184.45};
   Object^ result;
   Console::WriteLine();
   Console::WriteLine( "Invoking a method with parameters." );
   Console::WriteLine( "---------------------------------" );
   result = t->InvokeMember( "ComputeSum", BindingFlags::InvokeMethod, nullptr, nullptr, args );
   Console::WriteLine( " {0} + {1} = {2}", args[ 0 ], args[ 1 ], result );

   // BindingFlags::GetField, SetField
   Console::WriteLine();
   Console::WriteLine( "Invoking a field (getting and setting.)" );
   Console::WriteLine( "--------------------------------------" );

   // Get a field value.
   result = t->InvokeMember( "Name", BindingFlags::GetField, nullptr, c, noArguments );
   Console::WriteLine( "Name == {0}", result );

   // Set a field.
   array<Object^>^obj2 = {"NewName"};
   t->InvokeMember( "Name", BindingFlags::SetField, nullptr, c, obj2 );
   result = t->InvokeMember( "Name", BindingFlags::GetField, nullptr, c, noArguments );
   Console::WriteLine( "Name == {0}", result );
   Console::WriteLine();
   Console::WriteLine( "Invoking an indexed property (getting and setting.)" );
   Console::WriteLine( "--------------------------------------------------" );

   // BindingFlags::GetProperty
   // Get an indexed property value.
   int index = 3;
   array<Object^>^obj3 = {index};
   result = t->InvokeMember( "Item", BindingFlags::GetProperty, nullptr, c, obj3 );
   Console::WriteLine( "Item->Item[ {0}] == {1}", index, result );

   // BindingFlags::SetProperty
   // Set an indexed property value.
   index = 3;
   array<Object^>^obj4 = {index,"NewValue"};
   t->InvokeMember( "Item", BindingFlags::SetProperty, nullptr, c, obj4 );
   result = t->InvokeMember( "Item", BindingFlags::GetProperty, nullptr, c, obj3 );
   Console::WriteLine( "Item->Item[ {0}] == {1}", index, result );
   Console::WriteLine();
   Console::WriteLine( "Getting a field or property." );
   Console::WriteLine( "----------------------------" );

   // BindingFlags::GetField
   // Get a field or property.
   result = t->InvokeMember( "Name", static_cast<BindingFlags>(BindingFlags::GetField | 
       BindingFlags::GetProperty), nullptr, c, noArguments );
   Console::WriteLine( "Name == {0}", result );

   // BindingFlags::GetProperty
   result = t->InvokeMember( "Value", static_cast<BindingFlags>(BindingFlags::GetField | 
       BindingFlags::GetProperty), nullptr, c, noArguments );
   Console::WriteLine( "Value == {0}", result );
   Console::WriteLine();
   Console::WriteLine( "Invoking a method with named parameters." );
   Console::WriteLine( "---------------------------------------" );

   // BindingFlags::InvokeMethod
   // Call a method using named parameters.
   array<Object^>^argValues = {"Mouse","Micky"};
   array<String^>^argNames = {"lastName","firstName"};
   t->InvokeMember( "PrintName", BindingFlags::InvokeMethod, nullptr, nullptr, argValues, nullptr, 
       nullptr, argNames );
   Console::WriteLine();
   Console::WriteLine( "Invoking a default member of a type." );
   Console::WriteLine( "------------------------------------" );

   // BindingFlags::Default
   // Call the default member of a type.
   Type^ t3 = TestClass2::typeid;
   t3->InvokeMember( "", static_cast<BindingFlags>(BindingFlags::InvokeMethod | BindingFlags::Default), 
        nullptr, gcnew TestClass2, noArguments );

   // BindingFlags::Static, NonPublic, and Public
   // Invoking a member with ref parameters.
   Console::WriteLine();
   Console::WriteLine( "Invoking a method with ref parameters." );
   Console::WriteLine( "--------------------------------------" );
   MethodInfo^ m = t->GetMethod( "Swap" );
   args = gcnew array<Object^>(2);
   args[ 0 ] = 1;
   args[ 1 ] = 2;
   m->Invoke( gcnew TestClass, args );
   Console::WriteLine( "{0}, {1}", args[ 0 ], args[ 1 ] );

   // BindingFlags::CreateInstance
   // Creating an instance with a parameterless constructor.
   Console::WriteLine();
   Console::WriteLine( "Creating an instance with a parameterless constructor." );
   Console::WriteLine( "------------------------------------------------------" );
   Object^ obj = t->InvokeMember( "TestClass", static_cast<BindingFlags>(BindingFlags::Public | 
       BindingFlags::Instance | BindingFlags::CreateInstance), nullptr, nullptr, noArguments );
   Console::WriteLine("Instance of {0} created.", obj->GetType()->Name);

   // Creating an instance with a constructor that has parameters.
   Console::WriteLine();
   Console::WriteLine( "Creating an instance with a constructor that has parameters." );
   Console::WriteLine( "------------------------------------------------------------" );
   obj = t->InvokeMember( "TestClass", static_cast<BindingFlags>(BindingFlags::Public | 
       BindingFlags::Instance | BindingFlags::CreateInstance), nullptr, nullptr, 
       gcnew array<Object^> { "Hello, World!" } );
   Console::WriteLine("Instance of {0} created with initial value '{1}'.", obj->GetType()->Name, 
       obj->GetType()->InvokeMember("Name", BindingFlags::GetField, nullptr, obj, noArguments));

   // BindingFlags::DeclaredOnly
   Console::WriteLine();
   Console::WriteLine( "DeclaredOnly instance members." );
   Console::WriteLine( "------------------------------" );
   array<System::Reflection::MemberInfo^>^memInfo = t->GetMembers( BindingFlags::DeclaredOnly | 
       BindingFlags::Instance | BindingFlags::Public);
   for ( int i = 0; i < memInfo->Length; i++ )
   {
      Console::WriteLine( memInfo[ i ]->Name );

   }

   // BindingFlags::IgnoreCase
   Console::WriteLine();
   Console::WriteLine( "Using IgnoreCase and invoking the PrintName method." );
   Console::WriteLine( "---------------------------------------------------" );
   t->InvokeMember( "printname", static_cast<BindingFlags>(BindingFlags::IgnoreCase | 
                BindingFlags::Static | BindingFlags::Public | BindingFlags::InvokeMethod), 
                nullptr, nullptr, gcnew array<Object^> {"Brad","Smith"});

   // BindingFlags::FlattenHierarchy
   Console::WriteLine();
   Console::WriteLine( "Using FlattenHierarchy to get inherited static protected and public members." );
   Console::WriteLine( "----------------------------------------------------------------------------" );
   array<FieldInfo^>^ finfos = MostDerived::typeid->GetFields(BindingFlags::NonPublic | 
         BindingFlags::Public | BindingFlags::Static | BindingFlags::FlattenHierarchy);
   for each (FieldInfo^ finfo in finfos)
   {
       Console::WriteLine("{0} defined in {1}.", finfo->Name, finfo->DeclaringType->Name);
   }

   Console::WriteLine();
   Console::WriteLine("Without FlattenHierarchy." );
   Console::WriteLine("-------------------------");
   finfos = MostDerived::typeid->GetFields(BindingFlags::NonPublic | BindingFlags::Public |
         BindingFlags::Static);
   for each (FieldInfo^ finfo in finfos)
   {
       Console::WriteLine("{0} defined in {1}.", finfo->Name, finfo->DeclaringType->Name);
   }
};

/* This example produces output similar to the following:

Invoking a static method.
-------------------------
Hello

Invoking an instance method.
----------------------------
AddUp Called 1 times
AddUp Called 2 times

Invoking a method with parameters.
---------------------------------
 100.09 + 184.45 = 284.54

Invoking a field (getting and setting.)
--------------------------------------
Name == initialName
Name == NewName

Invoking an indexed property (getting and setting.)
--------------------------------------------------
Item->Item[ 3] == 3
Item->Item[ 3] == NewValue

Getting a field or property.
----------------------------
Name == NewName
Value == the value

Invoking a method with named parameters.
---------------------------------------
Mouse,Micky

Invoking a default member of a type.
------------------------------------
12/23/2009 4:19:06 PM

Invoking a method with ref parameters.
--------------------------------------
2, 1

Creating an instance with a parameterless constructor.
------------------------------------------------------
Instance of TestClass created.

Creating an instance with a constructor that has parameters.
------------------------------------------------------------
Instance of TestClass created with initial value 'Hello, World!'.

DeclaredOnly instance members.
------------------------------
get_Item
set_Item
get_Value
AddUp
PrintTime
Swap
.ctor
.ctor
Value
Item
Name
methodCalled

Using IgnoreCase and invoking the PrintName method.
---------------------------------------------------
Smith,Brad

Using FlattenHierarchy to get inherited static protected and public members.
----------------------------------------------------------------------------
DerivedOnly defined in Derived.
BaseOnly defined in Base.

Without FlattenHierarchy.
-------------------------

 */
using System;
using System.Reflection;
using System.IO;

namespace BindingFlagsSnippet
{
    class Example
    {
        static void Main()
        {
            // BindingFlags.InvokeMethod
            // Call a static method.
            Type t = typeof (TestClass);

            Console.WriteLine();
            Console.WriteLine("Invoking a static method.");
            Console.WriteLine("-------------------------");
            t.InvokeMember ("SayHello", BindingFlags.InvokeMethod | BindingFlags.Public |
                BindingFlags.Static, null, null, new object [] {});

            // BindingFlags.InvokeMethod
            // Call an instance method.
            TestClass c = new TestClass ();
            Console.WriteLine();
            Console.WriteLine("Invoking an instance method.");
            Console.WriteLine("----------------------------");
            c.GetType().InvokeMember ("AddUp", BindingFlags.InvokeMethod, null, c, new object [] {});
            c.GetType().InvokeMember ("AddUp", BindingFlags.InvokeMethod, null, c, new object [] {});

            // BindingFlags.InvokeMethod
            // Call a method with parameters.
            object [] args = new object [] {100.09, 184.45};
            object result;
            Console.WriteLine();
            Console.WriteLine("Invoking a method with parameters.");
            Console.WriteLine("---------------------------------");
            result = t.InvokeMember ("ComputeSum", BindingFlags.InvokeMethod, null, null, args);
            Console.WriteLine ("{0} + {1} = {2}", args[0], args[1], result);

            // BindingFlags.GetField, SetField
            Console.WriteLine();
            Console.WriteLine("Invoking a field (getting and setting.)");
            Console.WriteLine("--------------------------------------");
            // Get a field value.
            result = t.InvokeMember ("Name", BindingFlags.GetField, null, c, new object [] {});
            Console.WriteLine ("Name == {0}", result);
            // Set a field.
            t.InvokeMember ("Name", BindingFlags.SetField, null, c, new object [] {"NewName"});
            result = t.InvokeMember ("Name", BindingFlags.GetField, null, c, new object [] {});
            Console.WriteLine ("Name == {0}", result);

            Console.WriteLine();
            Console.WriteLine("Invoking an indexed property (getting and setting.)");
            Console.WriteLine("--------------------------------------------------");
            // BindingFlags.GetProperty
            // Get an indexed property value.
            int  index = 3;
            result = t.InvokeMember ("Item", BindingFlags.GetProperty, null, c, new object [] {index});
            Console.WriteLine ("Item[{0}] == {1}", index, result);
            // BindingFlags.SetProperty
            // Set an indexed property value.
            index = 3;
            t.InvokeMember ("Item", BindingFlags.SetProperty, null, c, new object [] {index, "NewValue"});
            result = t.InvokeMember ("Item", BindingFlags.GetProperty , null, c, new object [] {index});
            Console.WriteLine ("Item[{0}] == {1}", index, result);

            Console.WriteLine();
            Console.WriteLine("Getting a field or property.");
            Console.WriteLine("----------------------------");
            // BindingFlags.GetField
            // Get a field or property.
            result = t.InvokeMember ("Name", BindingFlags.GetField | BindingFlags.GetProperty, null, c,
                new object [] {});
            Console.WriteLine ("Name == {0}", result);
            // BindingFlags.GetProperty
            result = t.InvokeMember ("Value", BindingFlags.GetField | BindingFlags.GetProperty, null, c,
                new object [] {});
            Console.WriteLine ("Value == {0}", result);

            Console.WriteLine();
            Console.WriteLine("Invoking a method with named parameters.");
            Console.WriteLine("---------------------------------------");
            // BindingFlags.InvokeMethod
            // Call a method using named parameters.
            object[] argValues = new object [] {"Mouse", "Micky"};
            String [] argNames = new String [] {"lastName", "firstName"};
            t.InvokeMember ("PrintName", BindingFlags.InvokeMethod, null, null, argValues, null, null,
                argNames);

            Console.WriteLine();
            Console.WriteLine("Invoking a default member of a type.");
            Console.WriteLine("------------------------------------");
            // BindingFlags.Default
            // Call the default member of a type.
            Type t3 = typeof (TestClass2);
            t3.InvokeMember ("", BindingFlags.InvokeMethod | BindingFlags.Default, null, new TestClass2(),
                new object [] {});

            // BindingFlags.Static, NonPublic, and Public
            // Invoking a member with ref parameters.
            Console.WriteLine();
            Console.WriteLine("Invoking a method with ref parameters.");
            Console.WriteLine("--------------------------------------");
            MethodInfo m = t.GetMethod("Swap");
            args = new object[2];
            args[0] = 1;
            args[1] = 2;
            m.Invoke(new TestClass(),args);
            Console.WriteLine ("{0}, {1}", args[0], args[1]);

            // BindingFlags.CreateInstance
            // Creating an instance with a parameterless constructor.
            Console.WriteLine();
            Console.WriteLine("Creating an instance with a parameterless constructor.");
            Console.WriteLine("------------------------------------------------------");
            object cobj = t.InvokeMember ("TestClass", BindingFlags.Public |
                BindingFlags.Instance | BindingFlags.CreateInstance,
                null, null, new object [] {});
            Console.WriteLine("Instance of {0} created.", cobj.GetType().Name);

            // Creating an instance with a constructor that has parameters.
            Console.WriteLine();
            Console.WriteLine("Creating an instance with a constructor that has parameters.");
            Console.WriteLine("------------------------------------------------------------");
            cobj = t.InvokeMember ("TestClass", BindingFlags.Public |
                BindingFlags.Instance | BindingFlags.CreateInstance,
                null, null, new object [] { "Hello, World!" });
            Console.WriteLine("Instance of {0} created with initial value '{1}'.", cobj.GetType().Name,
                cobj.GetType().InvokeMember("Name", BindingFlags.GetField, null, cobj, null));

            // BindingFlags.DeclaredOnly
            Console.WriteLine();
            Console.WriteLine("DeclaredOnly instance members.");
            Console.WriteLine("------------------------------");
            System.Reflection.MemberInfo[] memInfo =
                t.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance |
                BindingFlags.Public);
            for(int i=0;i<memInfo.Length;i++)
            {
                Console.WriteLine(memInfo[i].Name);
            }

            // BindingFlags.IgnoreCase
            Console.WriteLine();
            Console.WriteLine("Using IgnoreCase and invoking the PrintName method.");
            Console.WriteLine("---------------------------------------------------");
            t.InvokeMember("printname", BindingFlags.IgnoreCase | BindingFlags.Static |
                BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new object[]
                {"Brad","Smith"});

            // BindingFlags.FlattenHierarchy
            Console.WriteLine();
            Console.WriteLine("Using FlattenHierarchy to get inherited static protected and public members." );
            Console.WriteLine("----------------------------------------------------------------------------");
            FieldInfo[] finfos = typeof(MostDerived).GetFields(BindingFlags.NonPublic | BindingFlags.Public |
                  BindingFlags.Static | BindingFlags.FlattenHierarchy);
            foreach (FieldInfo finfo in finfos)
            {
                Console.WriteLine("{0} defined in {1}.", finfo.Name, finfo.DeclaringType.Name);
            }

            Console.WriteLine();
            Console.WriteLine("Without FlattenHierarchy." );
            Console.WriteLine("-------------------------");
            finfos = typeof(MostDerived).GetFields(BindingFlags.NonPublic | BindingFlags.Public |
                  BindingFlags.Static);
            foreach (FieldInfo finfo in finfos)
            {
                Console.WriteLine("{0} defined in {1}.", finfo.Name, finfo.DeclaringType.Name);
            }
        }
    }

    public class TestClass
    {
        public String Name;
        private Object [] values = new Object [] {0, 1,2,3,4,5,6,7,8,9};

        public Object this [int index]
        {
            get
            {
                return values[index];
            }
            set
            {
                values[index] = value;
            }
        }

        public Object Value
        {
            get
            {
                return "the value";
            }
        }

        public TestClass () : this("initialName") {}
        public TestClass (string initName)
        {
            Name = initName;
        }

        int methodCalled = 0;

        public static void SayHello ()
        {
            Console.WriteLine ("Hello");
        }

        public void AddUp ()
        {
            methodCalled++;
            Console.WriteLine ("AddUp Called {0} times", methodCalled);
        }

        public static double ComputeSum (double d1, double d2)
        {
            return d1 + d2;
        }

        public static void PrintName (String firstName, String lastName)
        {
            Console.WriteLine ("{0},{1}", lastName,firstName);
        }

        public void PrintTime ()
        {
            Console.WriteLine (DateTime.Now);
        }

        public void Swap(ref int a, ref int b)
        {
            int x = a;
            a = b;
            b = x;
        }
    }

    [DefaultMemberAttribute ("PrintTime")]
    public class TestClass2
    {
        public void PrintTime ()
        {
            Console.WriteLine (DateTime.Now);
        }
    }

    public class Base
    {
        static int BaseOnlyPrivate = 0;
        protected static int BaseOnly = 0;
    }
    public class Derived : Base
    {
        public static int DerivedOnly = 0;
    }
    public class MostDerived : Derived {}
}

/* This example produces output similar to the following:

Invoking a static method.
-------------------------
Hello

Invoking an instance method.
----------------------------
AddUp Called 1 times
AddUp Called 2 times

Invoking a method with parameters.
---------------------------------
100.09 + 184.45 = 284.54

Invoking a field (getting and setting.)
--------------------------------------
Name == initialName
Name == NewName

Invoking an indexed property (getting and setting.)
--------------------------------------------------
Item[3] == 3
Item[3] == NewValue

Getting a field or property.
----------------------------
Name == NewName
Value == the value

Invoking a method with named parameters.
---------------------------------------
Mouse,Micky

Invoking a default member of a type.
------------------------------------
12/23/2009 4:29:21 PM

Invoking a method with ref parameters.
--------------------------------------
2, 1

Creating an instance with a parameterless constructor.
------------------------------------------------------
Instance of TestClass created.

Creating an instance with a constructor that has parameters.
------------------------------------------------------------
Instance of TestClass created with initial value 'Hello, World!'.

DeclaredOnly instance members.
------------------------------
get_Item
set_Item
get_Value
AddUp
PrintTime
Swap
.ctor
.ctor
Item
Value
Name

Using IgnoreCase and invoking the PrintName method.
---------------------------------------------------
Smith,Brad

Using FlattenHierarchy to get inherited static protected and public members.
----------------------------------------------------------------------------
DerivedOnly defined in Derived.
BaseOnly defined in Base.

Without FlattenHierarchy.
-------------------------

 */
Imports System.Reflection
Imports System.IO

Class Invoke

    Public Shared Sub Main()
        ' BindingFlags.InvokeMethod
        ' Call a static method.
        Dim t As Type = GetType(TestClass)

        Console.WriteLine()
        Console.WriteLine("Invoking a static method.")
        Console.WriteLine("-------------------------")
        t.InvokeMember("SayHello", BindingFlags.InvokeMethod Or BindingFlags.Public _
            Or BindingFlags.Static, Nothing, Nothing, New Object() {})

        ' BindingFlags.InvokeMethod
        ' Call an instance method.
        Dim c As New TestClass()
        Console.WriteLine()
        Console.WriteLine("Invoking an instance method.")
        Console.WriteLine("----------------------------")
        c.GetType().InvokeMember("AddUp", BindingFlags.InvokeMethod, Nothing, c, New Object() {})
        c.GetType().InvokeMember("AddUp", BindingFlags.InvokeMethod, Nothing, c, New Object() {})

        ' BindingFlags.InvokeMethod
        ' Call a method with parameters.
        Dim args() As Object = {100.09, 184.45}
        Dim result As Object
        Console.WriteLine()
        Console.WriteLine("Invoking a method with parameters.")
        Console.WriteLine("---------------------------------")
        result = t.InvokeMember("ComputeSum", BindingFlags.InvokeMethod, Nothing, Nothing, args)
        Console.WriteLine("{0} + {1} = {2}", args(0), args(1), result)

        ' BindingFlags.GetField, SetField
        Console.WriteLine()
        Console.WriteLine("Invoking a field (getting and setting.)")
        Console.WriteLine("--------------------------------------")
        ' Get a field value.
        result = t.InvokeMember("Name", BindingFlags.GetField, Nothing, c, New Object() {})
        Console.WriteLine("Name == {0}", result)
        ' Set a field.
        t.InvokeMember("Name", BindingFlags.SetField, Nothing, c, New Object() {"NewName"})
        result = t.InvokeMember("Name", BindingFlags.GetField, Nothing, c, New Object() {})
        Console.WriteLine("Name == {0}", result)

        Console.WriteLine()
        Console.WriteLine("Invoking an indexed property (getting and setting.)")
        Console.WriteLine("--------------------------------------------------")
        ' BindingFlags.GetProperty 
        ' Get an indexed property value.
        Dim index As Integer = 3
        result = t.InvokeMember("Item", BindingFlags.GetProperty, Nothing, c, New Object() {index})
        Console.WriteLine("Item[{0}] == {1}", index, result)
        ' BindingFlags.SetProperty
        ' Set an indexed property value.
        index = 3
        t.InvokeMember("Item", BindingFlags.SetProperty, Nothing, c, New Object() {index, "NewValue"})
        result = t.InvokeMember("Item", BindingFlags.GetProperty, Nothing, c, New Object() {index})
        Console.WriteLine("Item[{0}] == {1}", index, result)

        Console.WriteLine()
        Console.WriteLine("Getting a field or property.")
        Console.WriteLine("----------------------------")
        ' BindingFlags.GetField
        ' Get a field or property.
        result = t.InvokeMember("Name", BindingFlags.GetField Or BindingFlags.GetProperty, Nothing, _
            c, New Object() {})
        Console.WriteLine("Name == {0}", result)
        ' BindingFlags.GetProperty
        result = t.InvokeMember("Value", BindingFlags.GetField Or BindingFlags.GetProperty, Nothing, _
            c, New Object() {})
        Console.WriteLine("Value == {0}", result)

        Console.WriteLine()
        Console.WriteLine("Invoking a method with named parameters.")
        Console.WriteLine("---------------------------------------")
        ' BindingFlags.InvokeMethod
        ' Call a method using named parameters.
        Dim argValues() As Object = {"Mouse", "Micky"}
        Dim argNames() As [String] = {"lastName", "firstName"}
        t.InvokeMember("PrintName", BindingFlags.InvokeMethod, Nothing, Nothing, argValues, Nothing, _
            Nothing, argNames)

        Console.WriteLine()
        Console.WriteLine("Invoking a default member of a type.")
        Console.WriteLine("------------------------------------")
        ' BindingFlags.Default
        ' Call the default member of a type.
        Dim t3 As Type = GetType(TestClass2)
        t3.InvokeMember("", BindingFlags.InvokeMethod Or BindingFlags.Default, Nothing, _
            New TestClass2(), New Object() {})

        Console.WriteLine()
        Console.WriteLine("Invoking a method with ByRef parameters.")
        Console.WriteLine("----------------------------------------")
        ' BindingFlags.Static, NonPublic, and Public
        ' Invoking a member by reference.
        Dim m As MethodInfo = t.GetMethod("Swap")
        args = New Object(1) {}
        args(0) = 1
        args(1) = 2
        m.Invoke(New TestClass(), args)
        Console.WriteLine("{0}, {1}", args(0), args(1))

        ' BindingFlags.CreateInstance
        ' Creating an instance.
        Console.WriteLine()
        Console.WriteLine("Creating an instance with parameterless constructor.")
        Console.WriteLine("----------------------------------------------------")
        Dim obj As Object = GetType(TestClass).InvokeMember("TestClass", BindingFlags.CreateInstance, _
            Nothing, Nothing, New Object() {})
        Console.WriteLine("Instance of {0} created.", obj.GetType().Name)

        Console.WriteLine()
        Console.WriteLine("Creating an instance with a constructor that has parameters.")
        Console.WriteLine("------------------------------------------------------------")
        obj = GetType(TestClass).InvokeMember("TestClass", BindingFlags.CreateInstance, Nothing, _
            Nothing, New Object() { "Hello, World!" })
        Console.WriteLine("Instance of {0} created with initial value '{1}'.", obj.GetType().Name, _
            obj.GetType().InvokeMember("Name", BindingFlags.GetField, Nothing, obj, Nothing))

        ' BindingFlags.DeclaredOnly
        Console.WriteLine()
        Console.WriteLine("DeclaredOnly instance members.")
        Console.WriteLine("------------------------------")
        Dim memInfo As System.Reflection.MemberInfo() = t.GetMembers(BindingFlags.DeclaredOnly Or _
            BindingFlags.Public Or BindingFlags.Instance)
        Dim i As Integer
        For i = 0 To memInfo.Length - 1
            Console.WriteLine(memInfo(i).Name)
        Next i

        ' BindingFlags.IgnoreCase
        Console.WriteLine()
        Console.WriteLine("Using IgnoreCase and invoking the PrintName method.")
        Console.WriteLine("---------------------------------------------------")
        t.InvokeMember("printname", BindingFlags.IgnoreCase Or BindingFlags.Public Or _
            BindingFlags.Static Or BindingFlags.InvokeMethod, Nothing, Nothing, _
            New Object() {"Brad", "Smith"})

        ' BindingFlags.FlattenHierarchy
        Console.WriteLine()
        Console.WriteLine("Using FlattenHierarchy to get inherited static protected and public members." )
        Console.WriteLine("----------------------------------------------------------------------------")
        Dim finfos() As FieldInfo = GetType(MostDerived).GetFields(BindingFlags.NonPublic Or _
              BindingFlags.Public Or BindingFlags.Static Or BindingFlags.FlattenHierarchy)
        For Each finfo As FieldInfo In finfos
            Console.WriteLine("{0} defined in {1}.", finfo.Name, finfo.DeclaringType.Name)
        Next

        Console.WriteLine()
        Console.WriteLine("Without FlattenHierarchy." )
        Console.WriteLine("-------------------------")
        finfos = GetType(MostDerived).GetFields(BindingFlags.NonPublic Or BindingFlags.Public Or _
              BindingFlags.Static)
        For Each finfo As FieldInfo In finfos
            Console.WriteLine("{0} defined in {1}.", finfo.Name, finfo.DeclaringType.Name)
        Next
    End Sub
End Class

Public Class TestClass
    Public Name As String
    Private values() As [Object] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

    Default Public Property Item(ByVal index As Integer) As [Object]
        Get
            Return values(index)
        End Get
        Set(ByVal Value As [Object])
            values(index) = Value
        End Set
    End Property

    Public ReadOnly Property Value() As [Object]
        Get
            Return "the value"
        End Get
    End Property

    Public Sub New(ByVal initName As String)
        Name = initName
    End Sub 

    Public Sub New()
        MyClass.New("initialName")
    End Sub 

    Private methodCalled As Integer = 0

    Public Shared Sub SayHello()
        Console.WriteLine("Hello")
    End Sub 

    Public Sub AddUp()
        methodCalled += 1
        Console.WriteLine("AddUp Called {0} times", methodCalled)
    End Sub 

    Public Shared Function ComputeSum(ByVal d1 As Double, ByVal d2 As Double) As Double
        Return d1 + d2
    End Function 

    Public Shared Sub PrintName(ByVal firstName As [String], ByVal lastName As [String])
        Console.WriteLine("{0},{1}", lastName, firstName)
    End Sub 

    Public Sub PrintTime()
        Console.WriteLine(DateTime.Now)
    End Sub 

    Public Sub Swap(ByRef a As Integer, ByRef b As Integer)
        Dim x As Integer = a
        a = b
        b = x
    End Sub
End Class

<DefaultMemberAttribute("PrintTime")> _
Public Class TestClass2

    Public Sub PrintTime()
        Console.WriteLine(DateTime.Now)
    End Sub 
End Class

Public Class Base
    Shared BaseOnlyPrivate As Integer = 0
    Protected Shared BaseOnly As Integer = 0
End Class

Public Class Derived 
    Inherits Base
    Public Shared DerivedOnly As Integer = 0
End Class

Public Class MostDerived 
    Inherits Derived
End Class

' This example produces output similar to the following:
'
'Invoking a static method.
'-------------------------
'Hello
'
'Invoking an instance method.
'----------------------------
'AddUp Called 1 times
'AddUp Called 2 times
'
'Invoking a method with parameters.
'---------------------------------
'100.09 + 184.45 = 284.54
'
'Invoking a field (getting and setting.)
'--------------------------------------
'Name == initialName
'Name == NewName
'
'Invoking an indexed property (getting and setting.)
'--------------------------------------------------
'Item[3] == 3
'Item[3] == NewValue
'
'Getting a field or property.
'----------------------------
'Name == NewName
'Value == the value
'
'Invoking a method with named parameters.
'---------------------------------------
'Mouse,Micky
'
'Invoking a default member of a type.
'------------------------------------
'12/23/2009 4:34:22 PM
'
'Invoking a method with ByRef parameters.
'----------------------------------------
'2, 1
'
'Creating an instance with parameterless constructor.
'----------------------------------------------------
'Instance of TestClass created.
'
'Creating an instance with a constructor that has parameters.
'------------------------------------------------------------
'Instance of TestClass created with initial value 'Hello, World!'.
'
'DeclaredOnly instance members.
'------------------------------
'get_Item
'set_Item
'get_Value
'AddUp
'PrintTime
'Swap
'.ctor
'.ctor
'Item
'Value
'Name
'
'Using IgnoreCase and invoking the PrintName method.
'---------------------------------------------------
'Smith,Brad
'
'Using FlattenHierarchy to get inherited static protected and public members.
'----------------------------------------------------------------------------
'DerivedOnly defined in Derived.
'BaseOnly defined in Base.
'
'Without FlattenHierarchy.
'-------------------------
'

Remarques

Ces BindingFlags liaisons de contrôle pour un grand nombre de classes dans les Systemespaces de noms , System.Reflectionet System.Runtime qui appellent, créent, obtiennent, définissent et recherchent des membres et des types.

BindingFlags sont utilisés dans les méthodes suivantes Type et dans d’autres emplacements tels que MethodBase.Invoke:

InvokeMember et GetMethod sont particulièrement importants.

Les indicateurs de liaison peuvent être classés selon la façon dont ils identifient un membre de type, comme indiqué dans le tableau suivant.

Identifié par l’accessibilité Identifié par un argument de liaison Identifié par l’opération
DeclaredOnly

FlattenHierarchy

IgnoreCase

IgnoreReturn

Instance

Nonpublic

Public

statique
ExactBinding

OptionalParamBinding
CreateInstance

GetField

SetField

GetProperty

SetProperty

InvokeMethod

PutDispProperty

PutRefDispProperty

Notes

Vous devez spécifier Instance ou Static avec Public ou NonPublic aucun membre ne sera retourné.

Le tableau suivant répertorie les contraintes effectuées par la valeur par défaut Binder.ChangeType. Ce tableau s’applique en particulier à l’indicateur de BindingFlags.ExactBinding liaison. Le principe général est que ne doit effectuer que ChangeType des forçages élargis, qui ne perdent jamais de données. Un exemple de forçage élargi consiste à forcer une valeur qui est un entier signé 32 bits vers une valeur qui est un entier signé 64 bits. Cela se distingue d’une contrainte restrictive, qui peut perdre des données. Un exemple de contrainte restrictive est la force d’un entier signé 64 bits en entier signé 32 bits.

Type de source Type de cible
Tout type Son type de base.
Tout type Interface qu’il implémente.
Char UInt16, UInt32, Int32, UInt64, Int64, Single, Double
Byte Char, UInt16, Int16, UInt32, Int32, UInt64, Int64, Single, Double
SByte Int16, Int32, Int64, Single, Double
UInt16 UInt32, Int32, UInt64, Int64, Single, Double
Int16 Int32, Int64, Single, Double
UInt32 UInt64, Int64, Single, Double
Int32 Int64, Single, Double
UInt64 Single, Double
Int64 Single, Double
Single Double
Non-référence Par référence.

Lorsque l’indicateur de BindingFlags.ExactBinding liaison est utilisé, la réflexion modélise les règles d’accessibilité du système de type commun. Par exemple, si l’appelant se trouve dans le même assembly, l’appelant n’a pas besoin d’autorisations spéciales pour les membres internes. Sinon, l’appelant a besoin ReflectionPermissionde . Cela est cohérent avec la recherche de membres protégés, privés, etc.

S’applique à