将参数传递给动作调度程序

Pass parameter to action dispatcher

我有一个 class 从队列中调度 Actions。但是,我的 InvokeLater 只接受一个 Action,没有任何参数。

这是我的 Dispatcher:

public class Dispatcher : MonoBehaviour
{
    private static readonly Queue<Action> tasks = new Queue<Action>();
    public static Dispatcher Instance = null;

    static Dispatcher()
    {
        Instance = new Dispatcher();
    }

    private Dispatcher(){ }

    public void InvokeLater(Action task)
    {
        lock (tasks)
        {
            tasks.Enqueue(task);
        }
    }

    void FixedUpdate()
    {
        while (tasks.Count > 0)
        {
            Action task = null;

            lock (tasks)
            {
                if (tasks.Count > 0)
                {
                    task = tasks.Dequeue();
                }
            }

            task();
        }
    }
}

我是这样使用的:

var action = new Action(RequestPrediction);
Dispatcher.Instance.InvokeLater(action);

其中 RequestPrediction 是一个无参数函数——我想对其进行更改,以便它 (RequestPrediction) 接受一个 int 参数。

如何更改我的 Dispatcher 以便我可以执行以下操作:

var action = new Action(RequestPrediction);
Dispatcher.Instance.InvokeLater(action,5);

?

最简单的解决方案:

var action = new Action(() => RequestPrediction(5));
Dispatcher.Instance.InvokeLater(action);

否则,您将不得不开发自己的框架,并且最终会得到一些看起来像现有 TPL library in .NET or existing Dispatcher implementation 的东西。还有哪些更好的建议。

使用 lambda 函数。它将自动转换为 Action。而不是

var action = new Action(RequestPrediction);
Dispatcher.Instance.InvokeLater(action);

你可以使用

Action action = () => RequestPrediction();
Dispatcher.Instance.InvokeLater(action);

或者如果您更喜欢隐式类型的局部变量(var 关键字):

var action = new Action(() => RequestPrediction());
Dispatcher.Instance.InvokeLater(action);

这样可以在调用站点添加参数:

Action action = () => RequestPrediction(5);
Dispatcher.Instance.InvokeLater(action);

var action = new Action(() => RequestPrediction(5));
Dispatcher.Instance.InvokeLater(action);