![](/img/trans.png)
[英]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.