如何使用反射来调用方法和传递参数的类型是未知在编译时? [英] How to use reflection to call a method and pass parameters whose types are unknown at compile time?
问题描述
我想为调用类的方法与动态的参数值是经分析从字符串输入。
例如: 我想通过这些命令调用下面的程序:
For example: I'd like to call the following program with these commands:
C:> MYPROG.EXE治法System.Int32的777
C:> MYPROG.EXE治法System.float 23.17
C:> MYPROG.EXE方法b System.Int32的&放大器; 777
C:> MYPROG.EXE MethodC System.Int32的777 System.String ThisCanBeDone
c:>myprog.exe MethodA System.Int32 777
c:>myprog.exe MethodA System.float 23.17
c:>myprog.exe MethodB System.Int32& 777
c:>myprog.exe MethodC System.Int32 777 System.String ThisCanBeDone
static void Main(string[] args)
{
ClassA aa = new ClassA();
System.Type[] types = new Type[args.Length / 2];
object[] ParamArray = new object[types.Length];
for (int i=0; i < types.Length; i++)
{
types[i] = System.Type.GetType(args[i*2 + 1]);
// LINE_X: this will obviously cause runtime error invalid type/casting
ParamArray[i] = args[i*2 + 2];
MethodInfo callInfo = aa.GetType().GetMethod(args[0],types);
callInfo.Invoke(aa, ParamArray);
}
//在非可变CLASSLIB:
// In a non-changeable classlib:
公共类ClassA的 { 公共无效治法(int i)以{Console.Write(i.ToString()); }
public class ClassA { public void MethodA(int i) { Console.Write(i.ToString()); }
public void MethodA(float f) { Console.Write(f.ToString()); }
public void MethodB(ref int i) { Console.Write(i.ToString()); i++; }
public void MethodC(int i, string s) { Console.Write(s + i.ToString()); }
public void MethodA(object o) { Console.Write("Argg! Type Trapped!"); }
}
在上面的codeLINE_X是粘性的一部分。首先,我不知道如何为赋值给一个int或一个参考的int参数我创建它使用Activator.CreatInstance或别的东西,甚至后。该类型转换器也浮现在脑海中,但需要明确的编译型铸造为好。
"LINE_X" in the above code is the sticky part. For one, I have no idea how to assign value to a int or a ref int parameter even after I create it using Activator.CreatInstance or something else. The typeConverter does come to mind, but then that requires an explicit compile type casting as well.
我是看着CLR使用JavaScript眼镜还是有办法做到这一点?
Am I looking at CLR with JavaScript glasses or there is way to do this?
推荐答案
试试这个:
void Main(string[] args)
{
ClassA a = new ClassA();
System.Type[] types = new Type[(args.Length -1) / 2];
object[] ParamArray = new object[types.Length];
for (int i=0; i < types.Length; i++)
{
if(args[i*2 + 1].EndsWith("&"))
{
var type = System.Type.GetType(args[i*2 + 1].Substring(0,args[i*2 +1].Length - 1));
ParamArray[i] = Convert.ChangeType(args[i*2 + 2],type);
types[i] = System.Type.GetType(args[i*2 + 1]);
}
else
{
types[i] = System.Type.GetType(args[i*2 + 1]);
ParamArray[i] = Convert.ChangeType(args[i*2 + 2],types[i]);
}
}
MethodInfo callInfo = typeof(ClassA).GetMethod(args[0],types);
callInfo.Invoke(a, ParamArray);
}
编辑:这应该采取的基准参数保健
This should take care of the reference parameters
这篇关于如何使用反射来调用方法和传递参数的类型是未知在编译时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!