将任务与反思相结合

Wal*_*elt 2 c# reflection task-parallel-library .net-4.5

我有一个提供字符串列表的情况.列表中的第一个条目是方法的名称.列表中的其余字符串是方法参数.我想使用任务来运行该方法(用于教育目的).我在找出允许我将方法名称提供给Task指令的正确程序时遇到了问题.

对于此示例,我有两个可以作为任务运行的静态方法.args [1]意味着我的选择.

public class Program
{
    private static ILog log = LogManager.GetLogger 
                    (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    static void Main(string[] args)
    {
        string whichPrint = args[1];

        Type type = typeof(Program);
        MethodInfo meth = type.GetMethod(whichPrint, BindingFlags.Public | 
                                                           BindingFlags.Static);

        //this is the problem area....how do I feed the the method or delegate into 
        //the lambda expression ????
        Delegate methDel = meth.CreateDelegate(type);
        Task t = Task.Factory.StartNew(() => methDel("help!!"));

    }

    static void printme1(string s)
    {
        log.Debug("Printme1 Printing: " + s);
    }

    static void printme2(string s)
    {
        log.Debug("Printme2 Printing: " + s);
    }
}
Run Code Online (Sandbox Code Playgroud)

我无法编译,因为methDel被视为变量.我需要它或其他东西才能被视为一种方法.我不想使用case/switch语句,因为我可能有很多方法可以分配给任务.

Jon*_*eet 5

您要使用此功能创建新任务这一事实有点无关紧要.您需要做的就是找出如何调用该方法,其余的只是"启动一个新任务然后调用该方法".

所以你可能想要这样的东西:

public static void CallMethod(List<string> nameAndArguments)
{
    var method = typeof(Program).GetMethod(nameAndArguments[0]);
    method.Invoke(null, nameAndArguments.Skip(1).ToArray()):
}
Run Code Online (Sandbox Code Playgroud)

然后:

Task.Factory.StartNew(() => CallMethod(nameAndArguments));
Run Code Online (Sandbox Code Playgroud)

我不认为这是值得建立一个委托,除非你想获得更好的表现出来调用该委托的大量的时间.