现在的位置: 首页 > 综合 > 正文

关于.net中反射的一个小问题

2018年04月06日 ⁄ 综合 ⁄ 共 1127字 ⁄ 字号 评论关闭

若果一个函数有个参数是传引用的,比如ref 或者out,该如何得到被修改的结果呢?请看如下的代码

Int32[] input = new Int32{1,2};
txtOut.AppendText(input.Length.ToString() 
+ Environment.NewLine);

// txtOut is a multiline enabled textbox in my test form
MethodInfo info = typeof(Array).GetMethod("Resize").MakeGenericMethod(typeof(Int32));

Object[] paras 
= new Object[] { input, 4 }//如果是out型的,直接传个null就行。
info.Invoke(null, BindingFlags.InvokeMethod, null, paras, null);
input 
= paras[0as Int32[]; // get the written argument

CLR似乎会修改掉参数数组对象(paras)的引用,使其指向新的数组。 然后在其中存放输出结果。所以你就可以在修改后的数组中得到你想要的结果。顺便可以看一下对于泛型方法的实例化调用(MakeGenericMethod).

 

抱歉!评论已关闭.