gpt4 book ai didi

C# 动态方法调用任务作为一个 Action

转载 作者:行者123 更新时间:2023-11-30 21:04:28 27 4
gpt4 key购买 nike

我不喜欢 switch 语句。但是,我无法对以下情况产生任何替代想法。请给我一个想法。

// Parses MyTask object and routes for execution at a new task
private void PerformTask(MyTask task)
{
Action<object> taskAction = null;

// routing
switch (task.Command)
{
case "MethodX":
taskAction = MethodX;
break;

case "MethodY":
taskAction = MethodY;
break;

default:
break;
}

if (taskAction == null)
return;

Task t1 = Task.Factory.StartNew(taskAction, task);
}

private void MethodX(MyTask task)
{
// do it something
}

private void MethodY(MyTask task)
{
// do it something different
}

// task holder struct
public struct MyTask
{
public string Command;
public int[] Args;
public int Id;

public MyTask(string command, int[] args, int id)
{
this.Command = command;
this.Args = args;
this.Id = id;
}

}

// Gets next task as a MyTask object and performs it.
// Thread method that is polls task queue
private void DoSomeWorks()
{
...
MyTask task = GetNextTask();
PerformTask(task);
...
}

我有一些不同的任务应该异步运行。这些作为 MyTask 结构保存。

DoSomeWorks 方法中,下一个任务从我的任务队列中取出,然后传递给PerformTask 方法执行。 PerformTask 方法 (nitty-gritty) 确定将为任务处理哪个方法。我刚刚用 switch case 语句实现了这个路由操作。但是,我想动态地执行此操作。如何使用命令字符串动态调用方法?

我试过这样的东西;

MethodInfo methodInfo = typeof(MyClass).GetMethod(task.Command);

但我无法从 MethodInfo 转换为 Action。嗯,我需要帮助。

编辑:
感谢您的回答。我已经尝试了这两个建议。这就是我需要的:

private void PerformTask(MyTask task)
{
MethodInfo methodInfo = typeof(MyClass).GetMethod(task.Command);

if (methodInfo != null)
Task.Factory.StartNew(() => methodInfo.Invoke(this, new object[] { task }));
}

我不再需要 Action 对象了。所以,我可以将通用参数对象传递给方法。非常感谢

最佳答案

关于:

MethodInfo methodInfo = typeof(MyClass).GetMethod(task.Command);
if (methodInfo != null)
Task.Factory.StartNew(() => methodInfo.Invoke(this, new []{ task }));

关于C# 动态方法调用任务作为一个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12334639/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com