Ali*_*ali -2 c# asp.net reflection
我上课了
private class MyRouter
{
public string Json {get;set;}
public string Class { get; set; }
public string Method { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
它必须通过Json Arg调用Class中的Method,我怎样才能通过Reflection实现它?我做了这个,但没有任何帮助
MyRouter MR = new MyRouter(){initilising the class};
Assembly assembly = Assembly.Load("Common");
Type t = assembly.GetType("Common." + MR.Class);
var x = t.GetMethod(MR.Method ).Invoke(MR.Json,null);
Run Code Online (Sandbox Code Playgroud)
请参阅MethodBase.Invoke的文档:
第一个参数:
要调用方法或构造函数的对象.[...]
第二个参数:
调用的方法或构造函数的参数列表.[...]
这意味着您需要一个类的实例,例如通过执行以下操作
ConstructorInfo constr = t.GetConstructor(Type.EmptyTypes);
object myObj = constr.Invoke(new object[]{});
Run Code Online (Sandbox Code Playgroud)
然后,您可以在该实例上调用您的方法并传递您的JSONas参数:
var x = t.GetMethod(MR.Method).Invoke(myObj,MR.Json);
Run Code Online (Sandbox Code Playgroud)