Export (0) Print
Expand All
2 out of 4 rated this helpful - Rate this topic

Type.InvokeMember Method (String, BindingFlags, Binder, Object, Object[])

.NET Framework 1.1

Invokes the specified member, using the specified binding constraints and matching the specified argument list.

[Visual Basic]
Overloads Public Function InvokeMember( _
   ByVal name As String, _
   ByVal invokeAttr As BindingFlags, _
   ByVal binder As Binder, _
   ByVal target As Object, _
   ByVal args() As Object _
) As Object
[C#]
public object InvokeMember(
 string name,
 BindingFlags invokeAttr,
 Binder binder,
 object target,
 object[] args
);
[C++]
public: Object* InvokeMember(
 String* name,
 BindingFlags invokeAttr,
 Binder* binder,
 Object* target,
 Object* args __gc[]
);
[JScript]
public function InvokeMember(
   name : String,
 invokeAttr : BindingFlags,
 binder : Binder,
 target : Object,
 args : Object[]
) : Object;

Parameters

name
The String containing the name of the constructor, method, property, or field member to invoke.

-or-

An empty string ("") to invoke the default member.

invokeAttr
A bitmask comprised of one or more BindingFlags that specify how the search is conducted. The access can be one of the BindingFlags such as Public, NonPublic, Private, InvokeMethod, GetField, and so on. The type of lookup need not be specified. If the type of lookup is omitted, BindingFlags.Public | BindingFlags.Instance will apply.
binder
A Binder 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.

-or-

A null reference (Nothing in Visual Basic), to use the DefaultBinder.

target
The Object on which to invoke the specified member.
args
An array containing the arguments to pass to the member to invoke.

Return Value

An Object representing the return value of the invoked member.

Exceptions

Exception Type Condition
ArgumentNullException invokeAttr contains CreateInstance and typeName is a null reference (Nothing in Visual Basic).
ArgumentException args is multidimensional.

-or-

invokeAttr is not a valid BindingFlags attribute.

-or-

invokeAttr contains CreateInstance combined with InvokeMethod, GetField, SetField, GetProperty, or SetProperty.

-or-

invokeAttr contains both GetField and SetField.

-or-

invokeAttr contains both GetProperty and SetProperty.

-or-

invokeAttr contains InvokeMethod combined with SetField or SetProperty.

-or-

invokeAttr contains SetField and args has more than one element.

-or-

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.

-or-

One of the named parameter arrays contains a string that is a null reference (Nothing in Visual Basic).

MethodAccessException The specified member is a class initializer.
MissingFieldException The field or property cannot be found.
MissingMethodException The method cannot be found.
TargetException The specified member cannot be invoked on target.
AmbiguousMatchException More than one method matches the binding criteria.

Remarks

The following BindingFlags filter flags can be used to define which members to include in the search:

  • You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.
  • Specify BindingFlags.Public to include public members in the search.
  • Specify BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
  • Specify BindingFlags.FlattenHierarchy to include static members up the hierarchy.

The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase to ignore the case of name.
  • BindingFlags.DeclaredOnly to search only the members declared on the Type, not members that were simply inherited.

The following BindingFlags invocation flags can be used to denote what action to take with the member:

  • CreateInstance to invoke a constructor. name is ignored. Not valid with other invocation flags.
  • InvokeMethod to invoke a method, but not a constructor or a type initializer. Not valid with SetField or SetProperty.
  • GetField to get the value of a field. Not valid with SetField.
  • SetField to set the value of a field. Not valid with GetField.
  • GetProperty to get a property. Not valid with SetProperty.
  • SetProperty to set a property. Not valid with GetProperty.

See System.Reflection.BindingFlags for more information.

A method will be invoked if the following conditions are true:

  • The number of parameters in the method declaration equals the number of arguments in the args array (unless default arguments are defined on the member), and
  • The type of each arguments can be converted by the binder to the type of the parameter.

The binder will find all of the matching methods. These methods are found based upon the type of binding requested (BindingFlags values InvokeMethod, GetProperty, and so on). The set of methods is filtered by the name, number of arguments, and a set of search modifiers defined in the binder.

After the method is selected, it is invoked. Accessibility is checked at that point. The search may control which set of methods are searched based upon the accessibility attribute associated with the method. The Binder.BindToMethod method of the Binder class is responsible for selecting the method to be invoked. The default binder selects the most specific match.

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.

You can use Type.InvokeMember to set a field to a particular value by specifying BindingFlags.SetField. 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"});

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"});

which will initialize the field F to this new array. 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"});

This will change string "z" in the array that F holds to string "b".

Example

[Visual Basic, C#, C++] The following example uses InvokeMember to access members of a type.

[Visual Basic] 
Imports System
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 'New

    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 'MyType

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 'Main
End Class 'MyApp

[C#] 
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);
    }
}

[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::Reflection;

// This sample class has a field, constructor, method, and property.
__gc class MyType 
{
   Int32 myField;
public:
   MyType(Int32 __gc * x)
   {
      *x *= 5;
   }
   String* ToString()
   {
      return myField.ToString();
   }
   __property Int32 get_MyProp()
   {
         return myField;
   }
   __property void set_MyProp( Int32 value)
   { 
      if (value < 1) 
         throw new ArgumentOutOfRangeException(S"value", __box(value), S"value must be > 0");
      myField = value;
   }
};

int main() 
{
   Type* t = __typeof(MyType);
   // Create an instance of a type.
   Object* args[] = {__box(8)};
   Console::WriteLine(S"The value of x before the constructor is called is {0}.", args[0]);
   Object* obj = t->InvokeMember(0, 
      static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | 
      BindingFlags::Instance | BindingFlags::CreateInstance), 0, 0, args);
   Console::WriteLine(S"Type: {0}", obj->GetType());
   Console::WriteLine(S"The value of x after the constructor returns is {0}.", args[0]);

   // Read and write to a field.
   Object* obj5[] = {__box(5)};
   t->InvokeMember(S"myField", 
      static_cast<BindingFlags>(BindingFlags::DeclaredOnly | 
      BindingFlags::Public | BindingFlags::NonPublic | 
      BindingFlags::Instance | BindingFlags::SetField), 0, obj, obj5);
   Int32 v = *__try_cast<Int32 __gc *>( t->InvokeMember(S"myField", 
      static_cast<BindingFlags>(BindingFlags::DeclaredOnly | 
      BindingFlags::Public | BindingFlags::NonPublic | 
      BindingFlags::Instance | BindingFlags::GetField), 0, obj, 0) );
   Console::WriteLine(S"myField: {0}", __box(v));

   // Call a method.
   String* s = __try_cast<String*>( t->InvokeMember(S"ToString", 
      static_cast<BindingFlags>(BindingFlags::DeclaredOnly | 
      BindingFlags::Public | BindingFlags::NonPublic | 
      BindingFlags::Instance | BindingFlags::InvokeMethod), 0, obj, 0) );
   Console::WriteLine(S"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. 
      Object* obj0[] = {__box(0)};
      t->InvokeMember(S"MyProp", 
         static_cast<BindingFlags>(BindingFlags::DeclaredOnly | 
         BindingFlags::Public | BindingFlags::NonPublic | 
         BindingFlags::Instance | BindingFlags::SetProperty), 0, obj, obj0);
   } catch (TargetInvocationException* e) {
      // If the property assignment failed for some unexpected
      // reason, rethrow the TargetInvocationException.
      if (e->InnerException->GetType() != 
         __typeof(ArgumentOutOfRangeException)) 
         throw;
      Console::WriteLine(S"An invalid value was assigned to MyProp.");
   }
   Object* obj2[] = {__box(2)};
   t->InvokeMember(S"MyProp", 
      static_cast<BindingFlags>(BindingFlags::DeclaredOnly | 
      BindingFlags::Public | BindingFlags::NonPublic | 
      BindingFlags::Instance | BindingFlags::SetProperty), 0, obj, obj2);
   v = *__try_cast<Int32 __gc *>( t->InvokeMember(S"MyProp", 
      static_cast<BindingFlags>(BindingFlags::DeclaredOnly | 
      BindingFlags::Public | BindingFlags::NonPublic | 
      BindingFlags::Instance | BindingFlags::GetProperty), 0, obj, 0) );
   Console::WriteLine(S"MyProp: {0}", __box(v));
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

.NET Framework Security: 

See Also

Type Class | Type Members | System Namespace | Type.InvokeMember Overload List | String | Binder | DefaultBinder | BindingFlags | ParameterModifier | ParameterAttributes | CultureInfo | ReflectionPermission

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.