摘要:话说有一天你要用反射来对Target类进行操作,调用Foo函数。 public class Target
...{
public void Foo(int x, int y, int z)
...{
}
public void Foo(int x, ref int y, out int z)
...{
}
}
可以看到Foo有2个重载,唯一的区别在于第二个Foo方法签名中有带ref的参数。
如果你直接写:
Target myTarget = new Target();
Type t = myTarget.GetType();
MethodInfo methodInfoWithRefParamters = t.GetMethod("Foo");
那么会在RunTime扔个Exception说: Ambiguous match found.
要想invoke第二个Foo的话,我们必须这样写: MethodInfo methodInfoWithRefParamters ;Type[] typeList = new Type[] {typeof(int), Type.GetType("System.Int32&"),Type.GetType("System.Int32&") };methodInfoWithRefParamters = t.GetMethod("Foo", typeList );
好吧,现在运行是正常运行了,可是新的问题又来了:这个System.Int32&是个啥东东呢?
先在MSDN/.Net Reflector找找Int32&,没有。Google和查看微软放出的Framework Source Code,同样无果。
得,现成的资料找不到,那只有让我们自己通过做试验来玩玩了。
1。 先试试能不能搞一个Int32&的实例出来: 当然,就不用指望直接能在C#里面new一个Int32&了。(如果是unsafe的话,Int32*到还可以) 来试试亲爱的Activator吧: Type refInt32Type = Type.GetType("System.Int32&");
object myRefInt = System.Activator.CreateInstance(refInt32Type, true);
哎呀,扔了一个“No parameterless constructor defined......[
阅读全文]