如何使用 MethodInfo.Invoke 将参数作为引用传递 [英] How to pass a parameter as a reference with MethodInfo.Invoke

查看:42
本文介绍了如何使用 MethodInfo.Invoke 将参数作为引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I pass a parameter as a reference with MethodInfo.Invoke?

这是我要调用的方法:

private static bool test(string str, out byte[] byt)

我试过了,但失败了:

byte[] rawAsm = new byte[]{};
MethodInfo _lf = asm.GetType().GetMethod("test", BindingFlags.Static |  BindingFlags.NonPublic);
bool b = (bool)_lf.Invoke(null, new object[]
{
    "test",
    rawAsm
});

返回的字节为空.

推荐答案

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

You need to create the argument array first, and keep a reference to it. The out parameter value will then be stored in the array. So you can use:

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

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

Note how you don't need to provide the value for the second argument, because it's an out parameter - the value will be set by the method. If it were a ref parameter (instead of out) then the initial value would be used - but the value in the array could still be replaced by the method.

简短但完整的示例:

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

这篇关于如何使用 MethodInfo.Invoke 将参数作为引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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