C# 如何使用 MethodInfo.Invoke 将参数作为引用传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8779731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a parameter as a reference with MethodInfo.Invoke
提问by method
How can I pass a parameter as a reference with MethodInfo.Invoke?
如何将参数作为引用传递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.
返回的字节为空。
采纳答案by Jon Skeet
You need to create the argument array first, and keep a reference to it. The outparameter value will then be stored in the array. So you can use:
您需要先创建参数数组,并保留对它的引用。然后out参数值将存储在数组中。所以你可以使用:
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 outparameter - the value will be set by the method. If it were a refparameter (instead of out) then the initial value would be used - but the value in the array could still be replaced by the method.
请注意,您不需要为第二个参数提供值,因为它是一个out参数 - 该值将由方法设置。如果它是一个ref参数(而不是out),则将使用初始值 - 但数组中的值仍然可以由方法替换。
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";
}
}
回答by JaredPar
When a method invoked by reflection has a refparameter 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.
当反射调用的方法有一个ref参数时,它将被复制回用作参数列表的数组中。因此,要获得复制的回引用,您只需查看用作参数的数组。
object[] args = new [] { "test", rawAsm };
bool b = (bool)_lf.Invoke(null, args);
After this call args[1]will have the new byte[]
此调用args[1]后将有新的byte[]

