为什么不能使用Type.InvokeMember检索类型为out或ref的参数的值? [英] Why can't I retrieve the value for parameters of type out or ref using Type.InvokeMember?
问题描述
很长的标题,但我希望它具体.标题确实是个问题.即使 InvokeMember
所调用的方法具有一个 out
参数,并且正在将值分配给该参数,但我无法获取该值.这是我最初使用的代码:
A long title, but I wanted it to be specific. The title is really the question. Even though the method that InvokeMember
is calling has an out
parameter and is assigning a value to to that parameter I can't grab that value. Here is the code I was initially using:
string parameter = "";
int result = Convert.ToInt32(typeof(Ability).InvokeMember(selectedMove, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new object[] { parameter }));
我对此进行了更改,现在可以使其按预期运行,但我不知道为什么:
I changed it this, which now makes it work as intended but I don't know why:
object[] args = new object[1]; //necessary to retrieve ref/out parameter
int result = Convert.ToInt32(typeof(Ability).InvokeMember(selectedMove, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, args));
推荐答案
在您的第一个代码示例中,对 InvokeMember
的调用不会修改 parameter
的值变量,它仅替换参数数组中的第一项(现在指向另一个 string
实例).由于未保留对此数组的引用,因此无法检索输出参数的值.
In your first code example, the call to InvokeMember
doesn't modify the value of the parameter
variable, it just replaces the first item in the parameter array (which now points to a different string
instance). Since you didn't keep a reference to this array, you can't retrieve the value of the output parameter.
换句话说:该数组最初包含 parameter
变量的副本(即,对空字符串的引用的副本).调用后, parameter
和数组中的值引用2个不同的字符串实例.
In other words: the array initially contains a copy of the parameter
variable (i.e. a copy of the reference to an empty string). After the call, parameter
and the value in the array refer to 2 different string instances.
这篇关于为什么不能使用Type.InvokeMember检索类型为out或ref的参数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!