【问题标题】:How to pass a parameter as a reference with MethodInfo.Invoke如何使用 MethodInfo.Invoke 将参数作为引用传递
【发布时间】:2012-02-05 11:23:56
【问题描述】:

如何使用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
});

返回的字节为空。

【问题讨论】:

    标签: c# reflection methodinfo


    【解决方案1】:

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

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

    注意您不需要为第二个参数提供值,因为它是一个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";
        }
    }
    

    【讨论】:

      【解决方案2】:

      当反射调用的方法具有ref 参数时,它将被复制回用作参数列表的数组中。因此,要获得复制的反向引用,您只需查看用作参数的数组。

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

      在此调用后args[1] 将拥有新的byte[]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-09
        相关资源
        最近更新 更多