使用反射调用静态方法时,如何通过ref传递参数? [英] How do you pass parameters by ref when calling a static method using reflection?

查看:60
本文介绍了使用反射调用静态方法时,如何通过ref传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

如何通过ref传递参数,而不是按值传递参数?我认为默认情况下它们将是值.第一个参数(数组中的"Parameter1")应为ref,但我不知道如何以这种方式传递它.

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.

推荐答案

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

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"
  }
}

这篇关于使用反射调用静态方法时,如何通过ref传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆