如何通过一个参数与MethodInfo.Invoke参考 [英] How to pass a parameter as a reference with 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)
我试过,但我失败了:
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.
推荐答案
您需要先创建参数数组,并保持对它的引用。那么退出
参数值将被存储在数组中为止。所以,你可以使用:
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];
请注意,你怎么不需要提供第二个参数的值,因为它是一个退出
参数 - 值将由方法设置。如果它是一个 REF
参数(而不是退出
),那么将使用的初始值 - 但在价值阵列可以仍然通过该方法来代替。
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屋!