samedi 28 octobre 2017

How to InvokeMember with OptionalParamBinding and named parameters?

If I have a method which has optional arguments as follows:

public void foo(string argA, string argB = "", string argC = "")
{
   /* ... */
}

I can invoke this function without passing the optional argC using code such as:

Type _T = // get type;

dynamic instance = Activator.CreateInstance(_T);

_T.InvokeMember("foo",
                BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding,
                null,
                instance,
                new object[] { "A", "B"},
                null,
                null,
                new string[] { "argA", "argB" });

However, if I only want to pass argA and argC, omitting the optional argB, this fails with "System.IndexOutOfRangeException: Index was outside the bounds of the array."

_T.InvokeMember("foo",
                BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding,
                null,
                instance,
                new object[] { "A", "C"},
                null,
                null,
                new string[] { "argA", "argC" });

I realise I could work out the missing argument names but that would first entail establishing the most specific member (via call to _T.GetMember) effectively replicating what would have been done if it was a direct call rather than via reflection.

But, is there a way of doing this directly on the InvokeMember call?

For background, the actual code I'm working on is within the TryInvokeMember of a System.Dynamic.DynamicObject based class which itself has been called passing only argA and argC.

Thanks.





Aucun commentaire:

Enregistrer un commentaire