How do you pass parameters by ref when calling a static method using reflection?

允我心安 提交于 2021-02-16 06:06:26

问题


I'm calling a static method on an object using reflection:

MyType.GetMethod("MyMethod", BindingFlags.Static).Invoke(null, new object[] { Parameter1, Parameter2 });

How do you pass parameters by ref, rather that by value? I assume they would be by value by default. The first parameter ("Parameter1" in the array) should be by ref, but I can't figure out how to pass it that way.


回答1:


For a reference parameter (or out in C#), reflection will copy the new value into the object array at the same position as the original parameter. You can access that value to see the changed reference.

public class Example {
  public static void Foo(ref string name) {
    name = "foo";
  }
  public static void Test() {
    var p = new object[1];
    var info = typeof(Example).GetMethod("Foo");
    info.Invoke(null, p);
    var returned = (string)(p[0]);  // will be "foo"
  }
}



回答2:


If you call Type.GetMethod and use the BindingFlag of just BindingFlags.Static, it won't find your method. Remove the flag or add BindingFlags.Public and it will find the static method.

public Test { public static void TestMethod(int num, ref string str) { } }

typeof(Test).GetMethod("TestMethod"); // works
typeof(Test).GetMethod("TestMethod", BindingFlags.Static); // doesn't work
typeof(Test).GetMethod("TestMethod", BindingFlags.Static
                                     | BindingFlags.Public); // works


来源:https://stackoverflow.com/questions/786679/how-do-you-pass-parameters-by-ref-when-calling-a-static-method-using-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!