Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvokeMember object[] parameters

Tags:

c#

object

The problem

This may be a very simple question, but it's had me stuck for some time: InvokeMember can accept an object[] representing the parameters needed to pass to the method. I have two objects (list of obj, string foo). I can pass either variable successfully to the method, but when I try and pass both I get a Method 'x' NotFound exception.

Details

Calling the method:

classtype.InvokeMember(someMethodName, 
            BindingFlags.Public | BindingFlags.InvokeMethod|BindingFlags.Static,
            null,
            null,
            new object[]{ someListOfObjects, stringValue});

The receiving Method:

public static string TestMethod(object foo)
{
    return "foo";
}

Notes: When passing new object[]{someListOfObjects} or new object[]{stringValue} I reach the destination method as expected, however when I try and pass both it fails to find the method. Is my incoming parameter on TestMethod correct?

When I change TestMethod to accept an object[], the method is never found.

like image 484
Aardvark Avatar asked Dec 27 '22 06:12

Aardvark


1 Answers

You're passing in an array with two elements, so it views that as the argument array, looking for a method with two parameters. You want to end up with an array of length 1, whose sole element is an object which also happens to be an array (of length 2).

Options:

  • Cast it to object so that it the compiler parameter array to build a wrapping array

    (object) new object[] { someListOfObjects, stringValue }
    
  • Create the array directly yourself:

    new object[] { new object[] { someListOfObjects, stringValue } }
    
  • Modify the TestMethod parameters to match the array:

    public static string TestMethod(List<object> foo, string bar)
    
like image 145
Jon Skeet Avatar answered Jan 10 '23 18:01

Jon Skeet