简体   繁体   English

使用Reflection调用带参考参数的方法

[英]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 is a reference param. 我需要调用带有2个普通参数的反射的void方法和作为参考参数的第三个参数。 I've seen many posts about the problem and all suggest to use the GetMethod function instead of InvokeMember. 我看过很多关于这个问题的帖子,并建议使用GetMethod函数而不是InvokeMember。 I've tried the InvokeMember and it works, someone can explain me why? 我尝试过InvokeMember并且它有效,有人可以解释我为什么?

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. 方法MyMethod编辑Class1的字段myfield。 Is my code correct or should i anyway use GetMethod? 我的代码是正确的还是我应该使用GetMethod?

GetMethod will provide you method metadata (MethodInfo), which can be used to explore the method and take appropriate action. GetMethod将为您提供方法元数据(MethodInfo),可用于探索方法并采取适当的操作。 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. 例如,如果方法不存在或找不到,则将MethodInfo设置为null,并且可以在方法上调用InvokeMemeber之前处理此方法。

InvokeMember as name suggests will just invoke the method specified in arguments. 顾名思义,InvokeMember将只调用参数中指定的方法。 If method is not found, it'll throw "MissingMethodException", so you are loosing the validation bit as offered by GetMethod. 如果找不到方法,它将抛出“MissingMethodException”,因此您将丢失GetMethod提供的验证位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM