如何使用反射调用方法 [英] How to invoke a method using Reflection

查看:130
本文介绍了如何使用反射调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 (...) { ... }
}

在excel表中,我们正在阅读关键字,我们需要使用Reflection调用该特定方法:

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

但是这两行代码给我抛出了一些语法错误.我在文件顶部使用了using System.Reflection;,但是错误仍然存​​在.

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.

推荐答案

不要将MethodInfo对象method传递给invoke调用,而是传递要在其上调用方法的对象.我看不到您可能可以执行此操作的对象.

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.

此外,Invoke具有两个参数(请参阅 MSDN ).因此,语法错误可能是您忘记了传递参数.

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

据我了解您的代码,您有一个包含一些要动态调用的方法名称的Excel工作表.正确的? 但是您不能只从Excel单元中获取.NET对象.

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.

如果需要一个对象来调用该方法,则需要创建一个对象并建立正确的状态来调用它.因此,您可能可以向excel工作表中添加更多数据,并使用它来设置对象.

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.

这篇关于如何使用反射调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆