对象链接与API扩展中的方法

本文关键字:方法 扩展 API 链接 对象 | 更新日期: 2023-09-27 18:16:07

所以我在寻找扩展/适应一个API在我自己的需要。我说的是Lego Mindstorms c# API。我正在围绕它构建自己的API(基于适配器模式),这样我就可以以更好的OO方式对机器人进行编程。

这是关于API如何工作的链接:Lego Mindstorms EV3 c# API

但是现在我被c# API处理砖块命令的一种非常奇怪的方式卡住了。

绝对不是OO-way…

示例:要向砖块发送命令,您需要有砖块的实例来发送命令。但是DirectCommand实例与砖块无关。

await brick.DirectCommand.TurnMotorAtPowerAsync(OutputPort.A, 50, 5000);

所以我想做的是使砖和DirectCommand松散耦合。

下面是另一个例子:执行一批命令。你必须写出所有的命令,然后执行某个方法。在当前的API中,没有办法循环遍历数组并添加堆栈元素,以便在稍后执行它们。

brick.BatchCommand.TurnMotorAtSpeedForTime(OutputPort.A, 50, 1000, false);
brick.BatchCommand.TurnMotorAtPowerForTime(OutputPort.C, 50, 1000, false);
brick.BatchCommand.PlayTone(50, 1000, 500);
await brick.BatchCommand.SendCommandAsync();

所以我要做的是:

创建一个类似PlayTone(..)的命令,将其添加到命令的arrayList中,然后循环遍历它…

List<Command> toBeExecuted = new List<Command>;
toBeExecuted.Add(DirectCommand.PlayTone(50, 1000, 500));
brick.DirectCommand(toBeExecuted[0]);

所以如果有人能帮忙…我很乐意。

对象链接与API扩展中的方法

不完全是它们的设计目的,但你能把它们作为任务列表排列起来,然后传递吗?

一样:

static void Main(string[] args)
{
    //---- queue commands into a "batch"
    List<Task> toBeExecuted  = new List<Task>();
    toBeExecuted.Add(Task.Run(() => dothing()));
    toBeExecuted.Add(Task.Run(() => dothing()));
    toBeExecuted.Add(Task.Run(() => dothing()));
    toBeExecuted.Add(Task.Run(() => dothing()));
    toBeExecuted.Add(Task.Run(() => dothing()));

    //---- elsewhere
    Task.WaitAll(toBeExecuted.ToArray()); //fire off the batch
    await brick.BatchCommand.SendCommandAsync(); //send to brick
}

用dothing()代替你想要排队的batchcommand:

.Add(Task.Run(() => brick.BatchCommand...()));