Search code examples
c#reflectiondictionaryhashtableinvokemember

Type.InvokeMember when method has a Dictionary parameter


I am getting a

Method 'MyNameSpace.MyClass.MyMethod' not found.

when I changed a parameter of MyMethod from Hashtable to Dictionary<string, string>.

The invoke call is

return = t.InvokeMember("MyMethod", (BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod), null, instance, params);

When I do

Type type = a.GetType(String.Concat(DLLName, ".MyClass"));
var methods = t.GetMethods();

methods contains MyMethod() so it is there.

Can anyone shed any light?

The params are

Object[] params = new Object[11];
...
params[5] = foo.myHashtable.Cast<DictionaryEntry>().ToDictionary(d => d.Key, d => d.Value);   
...

The MyMethod signature is

public MyMethodReturn MyMethod(Byte[] m, Hashtable d, Mutex mut, FileStream logFile, Hashtable t, Dictionary<string, Byte[]> fields, bool e, byte[] k, int hashCode, bool h, Byte[] mm)

Solution

  • You have:

    params[5] = foo.myHashtable.Cast<DictionaryEntry>()
                   .ToDictionary(d => d.Key, d => d.Value); 
    

    This creates a Dictionary<object,object>, which does not match the signature. This is because a DictionaryEntry has object Key {get;} and object Value {get;}, and the compiler is using those to infer the types for the dictionary (generic type inference).

    Try:

    params[5] = foo.myHashtable.Cast<DictionaryEntry>()
                   .ToDictionary(d => (string)d.Key, d => (byte[])d.Value); 
    

    This will create a Dictionary<string,byte[]>, which should match.