Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在使用反射调用静态方法时,如何通过ref传递参数?_C#_.net_Reflection - Fatal编程技术网

C# 在使用反射调用静态方法时,如何通过ref传递参数?

C# 在使用反射调用静态方法时,如何通过ref传递参数?,c#,.net,reflection,C#,.net,Reflection,我正在使用反射对对象调用静态方法: MyType.GetMethod("MyMethod", BindingFlags.Static).Invoke(null, new object[] { Parameter1, Parameter2 }); 如何通过ref传递参数,而不是通过值传递参数?我认为默认情况下,它们是默认值。第一个参数(“数组中的Parameter1”)应该是ref,但我不知道如何通过这种方式传递它。对于引用参数(或在C#中输出),反射会将新值复制到对象数组中与原始参数相同的位置

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

MyType.GetMethod("MyMethod", BindingFlags.Static).Invoke(null, new object[] { Parameter1, Parameter2 });
如何通过ref传递参数,而不是通过值传递参数?我认为默认情况下,它们是默认值。第一个参数(“数组中的Parameter1”)应该是ref,但我不知道如何通过这种方式传递它。

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

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

如果调用
Type.GetMethod
并仅使用
BindingFlags.Static的
BindingFlag
,它将找不到您的方法。删除标志或添加
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

你说得对。谢谢不是我最初问题的根源,但仍然是一个问题。