如何传递参数作为参考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
然后参数值将存储在数组中。所以你可以使用:
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";
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)