How to pass a parameter as a reference with MethodInfo.Invoke

天涯浪子 提交于 2019-11-26 13:48:41

问题


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

This is the method I want to call:

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

I tried this but I failed:

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

The bytes returned are null.


回答1:


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];

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.

Short but complete sample:

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:


When a method invoked by reflection has a ref parameter it will be copied back into the array that was used as an argument list. So to get the copied back reference you simply need to look at the array used as arguments.

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

After this call args[1] will have the new byte[]



来源:https://stackoverflow.com/questions/8779731/how-to-pass-a-parameter-as-a-reference-with-methodinfo-invoke

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!