C# 调用方法(反射)时如何传递参数?
我需要调用一个方法,传递一个int。使用下面的代码,我可以获取该方法,但不能传递参数。如何修复它C# 调用方法(反射)时如何传递参数?,c#,reflection,C#,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) }); b
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)
{
}
新对象[1]
部分是指定参数的方式,但您只是传入一个带有单个null
引用的数组。你想要:
int id = ...; // Whatever you want the value to be
object[] args = new object[] { id };
method.Invoke(obj, args);
(有关详细信息,请参阅文档。)
请注意,
method.Invoke
返回的是object
,而不是bool
,因此当前代码甚至无法编译。您可以将返回值强制转换为bool
,但在您的示例中,这对执行时没有帮助,因为myMethod
返回void,新对象[1]
部分是指定参数的方式,但您只是传递了一个带有单个null
引用的数组。你想要:
int id = ...; // Whatever you want the value to be
object[] args = new object[] { id };
method.Invoke(obj, args);
(有关详细信息,请参阅文档。)
请注意,method.Invoke
返回的是object
,而不是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);
}
}
只需使用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);
}
}
method.Invoke(this.obj,新对象[]{1/*id*/})代码>检查这里方法.Invoke(this.obj,新对象[]{1/*id*/})代码>检查这里