我需要调用一个带有反射的 void 方法,该方法有两个普通参数和一个作为引用参数的第三个参数。我看过很多关于这个问题的帖子,所有帖子都建议使用 GetMethod 函数而不是 InvokeMember。我已经尝试了 InvokeMember 并且它有效,有人可以向我解释为什么吗?
Class1 myreferenceparam = new Class1();
myobject.InvokeMember("MyMethod", BindingFlags.InvokeMethod | BindingFlags.Default, null, myobject, new object[] { myparam1, myparam2, myreferenceparam });
Response.Write(myreferenceparam.myfield);
方法MyMethod 编辑Class1 的字段myfield。我的代码是否正确,还是应该使用 GetMethod?
最佳答案
GetMethod 将为您提供方法元数据 (MethodInfo),可用于探索方法并采取适当的操作。例如,如果方法不存在或找不到,您将获得 MethodInfo 为 null,您可以在对该方法调用 InvokeMemeber 之前处理它。
InvokeMember 顾名思义将只调用参数中指定的方法。如果未找到方法,它将抛出“MissingMethodException”,因此您将丢失 GetMethod 提供的验证位。
关于c# - 使用反射调用具有引用参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3404041/