tags:

views:

56

answers:

1

Hi all, i need to call a void method with reflection that have 2 normal params and a third param that is a reference param. I've seen many posts about the problem and all suggest to use the GetMethod function instead of InvokeMember. I've tried the InvokeMember and it works, someone can explain me why?

Class1 myreferenceparam = new Class1();
myobject.InvokeMember("MyMethod", BindingFlags.InvokeMethod | BindingFlags.Default, null, myobject, new object[] { myparam1, myparam2, myreferenceparam });
Response.Write(myreferenceparam.myfield);

The method MyMethod edit the field myfield of the Class1. Is my code correct or should i anyway use GetMethod?

A: 

GetMethod will provide you method metadata (MethodInfo), which can be used to explore the method and take appropriate action. For Example, if method does not exists or could not be found, you'll get MethodInfo as null and you can handle this before calling InvokeMemeber on the method.

InvokeMember as name suggests will just invoke the method specified in arguments. If method is not found, it’ll throw "MissingMethodException", so you are loosing the validation bit as offered by GetMethod.

akapoor
but so InvokeMethod correctly call the method passing the param as reference? Because the changes the method called do seems to be reflected in the variable passed by reference even if i don't use GetMethod
Stefano
your code is fine, though you could have used used alternative method by getting methodinfo and then calling Invoke on the method info. There seems to be interesting article on this on msdn, which shows the performance side of these alternatives : http://msdn.microsoft.com/en-us/magazine/cc163759.aspx#S6
akapoor
i'm seeing that the InvokeMember is the slowest so i should use MemberInfo...
Stefano