Rediger

Del via


Type.InvokeMember Method

Definition

Invokes a specific member of the current Type.

Overloads

InvokeMember(String, BindingFlags, Binder, Object, Object[])

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

InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo)

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[])

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[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

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

public:
 System::Object ^ InvokeMember(System::String ^ name, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, System::Object ^ target, cli::array <System::Object ^> ^ args);
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);
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args);
member this.InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] -> obj
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
Public Function InvokeMember (name As String, invokeAttr As BindingFlags, binder As Binder, target As Object, args As Object()) As Object

Parameters

name
String

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

-or-

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

-or-

For IDispatch members, a string representing the DispID, for example "[DispID=3]".

invokeAttr
BindingFlags

A bitwise combination of the enumeration values 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 | BindingFlags.Static are used.

binder
Binder

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.

-or-

A null reference (Nothing in Visual Basic), to use the DefaultBinder. Note that explicitly defining a Binder object may be required for successfully invoking method overloads with variable arguments.

target
Object

The object on which to invoke the specified member.

args
Object[]

An array containing the arguments to pass to the member to invoke.

Returns

An object representing the return value of the invoked member.

Implements

Exceptions

invokeAttr does not contain CreateInstance and name is null.

invokeAttr is not a valid BindingFlags attribute.

-or-

invokeAttr does not contain one of the following binding flags: InvokeMethod, CreateInstance, GetField, SetField, GetProperty, or SetProperty.

-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 null.

The specified member is a class initializer.

The field or property cannot be found.

No method can be found that matches the arguments in args.

-or-

The current Type object represents a type that contains open type parameters, that is, ContainsGenericParameters returns true.

The specified member cannot be invoked on target.

More than one method matches the binding criteria.

The .NET Compact Framework does not currently support this method.

The method represented by name has one or more unspecified generic type parameters. That is, the method's ContainsGenericParameters property returns true.

Examples

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);
    }
}
open System
open System.Reflection

// This sample class has a field, constructor, method, and property.
type MyType() =
    let mutable myField = 0

    member _.MyType(x: int byref) =
        x <- x * 5
    
    override _.ToString() =
        string myField
    
    member _.MyProp
        with get () = myField
        and set value =
            if value < 1 then
                raise (ArgumentOutOfRangeException("value", value, "value must be > 0"))
            myField <- value

let t = typeof<MyType>
// Create an instance of a type.
let args = Array.zeroCreate<obj> 8
printfn $"The value of x before the constructor is called is {args[0]}."
let obj = t.InvokeMember(null,
    BindingFlags.DeclaredOnly |||
    BindingFlags.Public ||| BindingFlags.NonPublic |||
    BindingFlags.Instance ||| BindingFlags.CreateInstance, null, null, args)
printfn $"Type: {obj.GetType()}"
printfn $"The value of x after the constructor returns is {args[0]}."

// Read and write to a field.
t.InvokeMember("myField",
    BindingFlags.DeclaredOnly |||
    BindingFlags.Public ||| BindingFlags.NonPublic |||
    BindingFlags.Instance ||| BindingFlags.SetField, null, obj, Array.zeroCreate<obj> 5) |> ignore
let v = t.InvokeMember("myField",
    BindingFlags.DeclaredOnly |||
    BindingFlags.Public ||| BindingFlags.NonPublic |||
    BindingFlags.Instance ||| BindingFlags.GetField, null, obj, null) :?> int
printfn $"myField: {v}"

// Call a method.
let s = t.InvokeMember("ToString",
    BindingFlags.DeclaredOnly |||
    BindingFlags.Public ||| BindingFlags.NonPublic |||
    BindingFlags.Instance ||| BindingFlags.InvokeMethod, null, obj, null) :?> string
printfn $"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, Array.zeroCreate<obj> 0) |> ignore
with :? TargetInvocationException as e ->
    // If the property assignment failed for some unexpected
    // reason, rethrow the TargetInvocationException.
    if e.InnerException.GetType() <> typeof<ArgumentOutOfRangeException> then
        reraise ()
    printfn "An invalid value was assigned to MyProp."
t.InvokeMember("MyProp",
    BindingFlags.DeclaredOnly |||
    BindingFlags.Public ||| BindingFlags.NonPublic |||
    BindingFlags.Instance ||| BindingFlags.SetProperty, null, obj, Array.zeroCreate<obj> 2) |> ignore
let v2 = t.InvokeMember("MyProp",
    BindingFlags.DeclaredOnly |||
    BindingFlags.Public ||| BindingFlags.NonPublic |||
    BindingFlags.Instance ||| BindingFlags.GetProperty, null, obj, null)
printfn $"MyProp: {v2}"
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

Remarks

Note

You cannot use InvokeMember to invoke a generic method.

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

  • 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. If InvokeMethod is specified by itself, BindingFlags.Public, BindingFlags.Instance, and BindingFlags.Static are automatically included.

  • 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 both of 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 BindingFlags.OptionalParamBinding is specified).

  • The type of each argument 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's 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".

When you invoke an IDispatch member, you can specify the DispID instead of the member name, using the string format "[DispID=##]". For example, if the DispID of MyComMethod is 3, you can specify the string "[DispID=3]" instead of "MyComMethod". Invoking a member by DispID is faster than looking up the member by name. In complex aggregation scenarios, the DispID is sometimes the only way to invoke the desired member.

Note

Starting with the .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. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

See also

Applies to

InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo)

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

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

public:
 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:
 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);
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Globalization.CultureInfo culture);
member this.InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] * System.Globalization.CultureInfo -> obj
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
Public Function InvokeMember (name As String, invokeAttr As BindingFlags, binder As Binder, target As Object, args As Object(), culture As CultureInfo) As Object

Parameters

name
String

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

-or-

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

-or-

For IDispatch members, a string representing the DispID, for example "[DispID=3]".

invokeAttr
BindingFlags

A bitwise combination of the enumeration values 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 | BindingFlags.Static are used.

binder
Binder

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.

-or-

A null reference (Nothing in Visual Basic), to use the DefaultBinder. Note that explicitly defining a Binder object may be required for successfully invoking method overloads with variable arguments.

target
Object

The object on which to invoke the specified member.

args
Object[]

An array containing the arguments to pass to the member to invoke.

culture
CultureInfo

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.

-or-

A null reference (Nothing in Visual Basic) to use the current thread's CultureInfo.

Returns

An object representing the return value of the invoked member.

Implements

Exceptions

invokeAttr does not contain CreateInstance and name is null.

invokeAttr is not a valid BindingFlags attribute.

-or-

invokeAttr does not contain one of the following binding flags: InvokeMethod, CreateInstance, GetField, SetField, GetProperty, or SetProperty.

-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 null.

The specified member is a class initializer.

The field or property cannot be found.

No method can be found that matches the arguments in args.

-or-

The current Type object represents a type that contains open type parameters, that is, ContainsGenericParameters returns true.

The specified member cannot be invoked on target.

More than one method matches the binding criteria.

The method represented by name has one or more unspecified generic type parameters. That is, the method's ContainsGenericParameters property returns true.

Remarks

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.

Note

You cannot use InvokeMember to invoke a generic method.

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

  • Specify BindingFlags.Public to include public members in the search.

  • Specify BindingFlags.NonPublic to include non-public members (that is, private, internal, 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. If InvokeMethod is specified by itself, BindingFlags.Public, BindingFlags.Instance, and BindingFlags.Static are automatically included.

  • 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 both of 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 BindingFlags.OptionalParamBinding is specified).

  • The type of each argument 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's 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 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"}, null);

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

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

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

When you invoke an IDispatch member you can specify the DispID instead of the member name, using the string format "[DispID=##]". For example, if the DispID of MyComMethod is 3, you can specify the string "[DispID=3]" instead of "MyComMethod". Invoking a member by DispID is faster than looking up the member by name. In complex aggregation scenarios, the DispID is sometimes the only way to invoke the desired member.

Note

Starting with the .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. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

See also

Applies to

InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

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);
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
Public MustOverride Function InvokeMember (name As String, invokeAttr As BindingFlags, binder As Binder, target As Object, args As Object(), modifiers As ParameterModifier(), culture As CultureInfo, namedParameters As String()) As Object

Parameters

name
String

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

-or-

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

-or-

For IDispatch members, a string representing the DispID, for example "[DispID=3]".

invokeAttr
BindingFlags

A bitwise combination of the enumeration values 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 | BindingFlags.Static are used.

binder
Binder

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.

-or-

A null reference (Nothing in Visual Basic), to use the DefaultBinder. Note that explicitly defining a Binder object may be required for successfully invoking method overloads with variable arguments.

target
Object

The object on which to invoke the specified member.

args
Object[]

An array containing the arguments to pass to the member to invoke.

modifiers
ParameterModifier[]

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the args array. A parameter's associated attributes are stored in the member's signature.

The default binder processes this parameter only when calling a COM component.

culture
CultureInfo

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.

-or-

A null reference (Nothing in Visual Basic) to use the current thread's CultureInfo.

namedParameters
String[]

An array containing the names of the parameters to which the values in the args array are passed.

Returns

An object representing the return value of the invoked member.

Implements

Exceptions

invokeAttr does not contain CreateInstance and name is null.

args and modifiers do not have the same length.

-or-

invokeAttr is not a valid BindingFlags attribute.

-or-

invokeAttr does not contain one of the following binding flags: InvokeMethod, CreateInstance, GetField, SetField, GetProperty, or SetProperty.

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

The named parameter array is larger than the argument array.

-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 null.

The specified member is a class initializer.

The field or property cannot be found.

No method can be found that matches the arguments in args.

-or-

No member can be found that has the argument names supplied in namedParameters.

-or-

The current Type object represents a type that contains open type parameters, that is, ContainsGenericParameters returns true.

The specified member cannot be invoked on target.

More than one method matches the binding criteria.

The method represented by name has one or more unspecified generic type parameters. That is, the method's ContainsGenericParameters property returns true.

Remarks

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.

Note

You cannot use InvokeMember to invoke a generic method.

When you invoke an IDispatch member you can specify the DispID instead of the member name, using the string format "[DispID=##]". For example, if the DispID of MyComMethod is 3, you can specify the string "[DispID=3]" instead of "MyComMethod". Invoking a member by DispID is faster than looking up the member by name. In complex aggregation scenarios, the DispID is sometimes the only way to invoke the desired member.

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 is only used when calling through COM interop, and only parameters that are passed by reference are handled.

Each parameter in the namedParameters array gets the value in the corresponding element in the args array. If the length of args is greater than the length of namedParameters, the remaining argument values are passed in order.

The namedParameters array can be used to change the order of arguments in an input array. 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.

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

  • Specify BindingFlags.Public to include public members in the search.

  • Specify BindingFlags.NonPublic to include non-public members (that is, private, internal, 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. If InvokeMethod is specified by itself, BindingFlags.Public, BindingFlags.Instance, and BindingFlags.Static are automatically included.

  • 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 both of 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 BindingFlags.OptionalParamBinding is specified).

  • The type of each argument 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's 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.

InvokeMember can be used to invoke methods with parameters that have default values. To bind to these methods, Reflection requires BindingFlags.OptionalParamBinding to be specified. For a parameter that has a default value, you can either supply a different value, or supply Missing.Value to use the default value.

For example, consider a method such as MyMethod(int x, float y = 2.0). 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. Unless you use Missing.Value, you may not omit optional parameters with the Invoke method. If you must do so, use InvokeMember instead.

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

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

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

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

Note

Starting with the .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. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

See also

Applies to