在 C# 中使用名称调用方法 [英] Call methods using names in C#

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

问题描述

我的应用程序中有许多作业",其中每个作业都有一个需要调用的方法列表及其参数.本质上,一个包含以下对象的列表被称为:

I have a number of 'jobs' in my application, where each job has a list of methods which it needs to call, along with it's parameters. Essentially a list containing the following object is called:

string Name;
List<object> Parameters;

所以基本上,当一个作业运行时,我想通过这个列表进行枚举,并调用相关的方法.例如,如果我有一个如下所示的方法:

So basically, when a job runs I want to enumerate through this list, and call the relevant methods. For example, if I have a method like the following:

TestMethod(string param1, int param2)

我的方法对象是这样的:

My method object would be like this:

Name = TestMethod
Parameters = "astring", 3

可以这样做吗?我想反思将是这里的关键.

Is it possible to do this? I imagine reflection will be the key here.

推荐答案

当然,你可以这样做:

public class Test
{
    public void Hello(string s) { Console.WriteLine("hello " + s); }
}

...

{
     Test t = new Test();
     typeof(Test).GetMethod("Hello").Invoke(t, new[] { "world" }); 

     // alternative if you don't know the type of the object:
     t.GetType().GetMethod("Hello").Invoke(t, new[] { "world" }); 
}

Invoke() 的第二个参数是一个 Object 数组,其中包含要传递给您的方法的所有参数.

The second parameter of Invoke() is an array of Object containing all the parameters to pass to your method.

假设所有方法都属于同一个类,您可以拥有该类的方法,例如:

Assuming the methods all belong to the same class, you could have a method of that class something like:

public void InvokeMethod(string methodName, List<object> args)
{
    GetType().GetMethod(methodName).Invoke(this, args.ToArray());
}

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

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