如何编写简单的Actor

时间:2018-08-29 19:19:01

标签: c# actor covariance contravariance actor-model

我想编写一个类似于actor的类-因此,与其公开其方法,它没有一个命令处理程序,该命令处理程序将命令排队并将其分配给适当的方法。但是我不知道如何编译此代码-也许方法应该有所不同,但是我希望界面看起来像ICommandHandler。在我的实现中,由于签名不同,我无法向dictionary添加方法。

internal class Program
{
    private static void Main(string[] args)
    {
        new CommandHandler().InvokeCommand(new TurnOnCommand());
    }
}

public class CommandHandler : ICommandHandler
{
    private readonly Dictionary<Type, Func<Command, Task>> _handlers = new Dictionary<Type, Func<Command, Task>>();

    public CommandHandler()
    {
        // This will not compile - in final version this should be filled by reflection
        _handlers.Add(typeof(TurnOnCommand), HandleTurnOn);
        _handlers.Add(typeof(TurnOnCommand), TurnOffCommand);
    }

    public Task InvokeCommand(Command command)
    {
        // this will go to queue and than invoked
        _handlers[command.GetType()].Invoke(command);

        return Task.CompletedTask;
    }

    private Task HandleTurnOn(TurnOnCommand command)
    {
        return Task.CompletedTask;
    }

    private Task HandleTurnOff(TurnOffCommand command)
    {
        return Task.CompletedTask;
    }
}

public class Command
{
}

public class TurnOnCommand : Command
{
}

public class TurnOffCommand : Command
{
}

public interface ICommandHandler
{
    Task InvokeCommand(Command command);
}

0 个答案:

没有答案