【问题标题】:How do you pass parameters by ref when calling a static method using reflection?使用反射调用静态方法时如何通过 ref 传递参数?
【发布时间】:2009-04-24 16:44:28
【问题描述】:

我正在使用反射调用对象的静态方法:

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

如何通过 ref 传递参数,而不是通过值传递参数?我假设默认情况下它们是按价值计算的。第一个参数(数组中的“Parameter1”)应该是 ref,但我不知道如何以这种方式传递它。

【问题讨论】:

    标签: c# .net reflection


    【解决方案1】:

    对于引用参数(或 C# 中的 out),反射会将新值复制到对象数组中与原始参数相同的位置。您可以访问该值以查看更改的引用。

    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】:

      如果您调用Type.GetMethod 并使用BindingFlag 只是BindingFlags.Static,它将找不到您的方法。去掉flag或者加上BindingFlags.Public就会找到静态方法。

      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
      

      【讨论】:

      • 你是对的。谢谢。不是我原来问题的根源,但仍然是一个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多