开发者

Call a method with reference params with Reflection

i need to call a void method with reflection that have 2 normal params and a third param that开发者_C百科 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜