如何使用MethodInfo.Invoke传递参数作为引用

met*_*hod 37 c# reflection methodinfo

如何将参数作为参考传递MethodInfo.Invoke

这是我想要调用的方法:

private static bool test(string str, out byte[] byt)
Run Code Online (Sandbox Code Playgroud)

我尝试了这个,但我失败了:

byte[] rawAsm = new byte[]{};
MethodInfo _lf = asm.GetTypes()[0].GetMethod("test", BindingFlags.Static |  BindingFlags.NonPublic);
bool b = (bool)_lf.Invoke(null, new object[]
{
    "test",
    rawAsm
});
Run Code Online (Sandbox Code Playgroud)

返回的字节为空.

Jon*_*eet 57

您需要首先创建参数数组,并保持对它的引用.然后out参数值将存储在数组中.所以你可以使用:

object[] arguments = new object[] { "test", null };
MethodInfo method = ...;
bool b = (bool) method.Invoke(null, arguments);
byte[] rawAsm = (byte[]) arguments[1];
Run Code Online (Sandbox Code Playgroud)

请注意您不需要为第二个参数提供值,因为它是一个out参数 - 该值将由方法设置.如果它是一个ref参数(而不是out),那么将使用初始值 - 但是数组中的值仍然可以被该方法替换.

简短但完整的样本:

using System;
using System.Reflection;

class Test
{
    static void Main()
    {
        object[] arguments = new object[1];
        MethodInfo method = typeof(Test).GetMethod("SampleMethod");
        method.Invoke(null, arguments);
        Console.WriteLine(arguments[0]); // Prints Hello
    }

    public static void SampleMethod(out string text)
    {
        text = "Hello";
    }
}
Run Code Online (Sandbox Code Playgroud)


Jar*_*Par 12

当一个由reflect调用的方法有一个ref参数时,它将被复制回用作参数列表的数组.因此,要获得复制的返回引用,您只需要查看用作参数的数组.

object[] args = new [] { "test", rawAsm };
bool b = (bool)_lf.Invoke(null, args);
Run Code Online (Sandbox Code Playgroud)

这个电话args[1]会有新的byte[]