How to invoke a method using Reflection

穿精又带淫゛_ 提交于 2019-12-13 11:21:15

问题


for (int tsid = 1; tsid < controller.getRowCount(currentTest); tsid++)
{
    // values from xls
    keyword = controller.getCellData(currentTest, "Keyword", tsid);
    //object=controller.getCellData(currentTest, "Object", tsid);
    currentTSID = controller.getCellData(currentTest, "TSID", tsid);
    stepDescription = controller.getCellData(currentTest, "Description", tsid);

    Console.WriteLine("Keyword is:" + keyword);

    try
    {
        // --this is equivalent java code 
        //MethodInfo method= Keywords.class.getMethod(keyword);

        MethodInfo method= method.GetMethodBody(keyword);
        String result = (String)method.Invoke(method);

        if(!result.StartsWith("Fail")) {
            ReportUtil.addKeyword(stepDescription, keyword, result,null);
        }
    }
    catch (...) { ... }
}

Here from excel sheet we are reading the Keyword and we need to call that specific method using Reflection:

MethodInfo method= method.GetMethodBody(keyword);
String result = (String)method.Invoke(method);

But these two lines of code are throwing me some syntax error. I have used using System.Reflection; at the top of the file, but the error persists.


回答1:


In C# you don't use Type.class, instead you use typeof(Type).

You can use this in combination with GetMethod(string methodName) to get a specific MethodInfo, which you can then Invoke(object instance, object[] parameters). For static classes object instance should be null.

For example:

 typeof(Console).GetMethod("ReadLine").Invoke(null, new object[] { });



回答2:


Don't pass the MethodInfo Object method to the invoke call but instead the object on which you want to call the method. I can't see the object you probably could do this on.

Furthermore Invoke has two parameters (see MSDN). So the syntax error is probably that you forgot to pass the parameters.

As far as I understand your code you have an Excel sheet holding some method names which you want to call dynamically. Right? But you can't just get a .NET Object from a Excel cell.

If you need an object to call the method on, you'll need to create one and establish the correct state to call it. So you could probably add some more data to your excel sheet and use it to set up the object.




回答3:


May be for a Future reader, can use something like this..

keyWordHolder program = new keyWordHolder();
MethodInfo[] methods = typeof(keyWordHolder).GetMethods();
foreach (MethodInfo meth in methods)
 {
   if (meth.Name == keywords)
      {
          meth.Invoke(program, null); 
       }   


来源:https://stackoverflow.com/questions/20925962/how-to-invoke-a-method-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!