[英]How to do automatic type conversion for parameters when invoking a method using reflection in C#?
[英]How to pass an argument when invoking a method (reflection)?
我需要调用一个方法,并传递一个int值。 使用以下代码,我可以获取方法但不传递参数。 如何解决?
dynamic obj;
obj = Activator.CreateInstance(Type.GetType(String.Format("{0}.{1}", namespaceName, className)));
var method = this.obj.GetType().GetMethod(this.methodName, new Type[] { typeof(int) });
bool isValidated = method.Invoke(this.obj, new object[1]);
public void myMethod(int id)
{
}
new object[1]
部分是您如何指定参数的方法-但您只是传入具有单个null
引用的数组。 你要:
int id = ...; // Whatever you want the value to be
object[] args = new object[] { id };
method.Invoke(obj, args);
(有关更多详细信息,请参见MethodBase.Invoke
文档。)
请注意method.Invoke
返回object
,而不是bool
,因此您当前的代码甚至无法编译。 您可以将返回值bool
为bool
,但是在您的示例中,由于myMethod
返回void
,这在执行时无济于事。
只需使用invoke方法传递对象
namespace test
{
public class A
{
public int n { get; set; }
public void NumbMethod(int Number)
{
int n = Number;
console.writeline(n);
}
}
}
class MyClass
{
public static int Main()
{
test mytest = new test();
Type myTypeObj = mytest.GetType();
MethodInfo myMethodInfo = myTypeObj.GetMethod("NumbMethod");
object[] parmint = new object[] {5};
myMethodInfo.Invoke(myClassObj, parmint);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.