【问题标题】:How to pass an argument when invoking a method (reflection)?调用方法(反射)时如何传递参数?
【发布时间】:2014-06-27 21:51:26
【问题描述】:

我需要调用一个方法,传递一个 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)
{
}

【问题讨论】:

标签: c# reflection


【解决方案1】:

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,但在您的示例中,这在执行时无济于事,因为myMethod 返回void

【讨论】:

    【解决方案2】:

    只需通过调用方法传递一个对象

    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);
        }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      相关资源
      最近更新 更多