Tuesday, 20 August 2013

Delegate types and covariance with a generic delegate type

Delegate types and covariance with a generic delegate type

I would like to maintain a list of delegates (here: "mCommandHandlers").
Since they're generic delegates, I actually defined a second type of
delegates such that I can maintain such a list:
public delegate void CommandHandler<TCommand>(TCommand command) where
TCommand : ICommand;
public delegate void ICommandHandler(ICommand command);
Dictionary<Type, ICommandHandler> mCommandHandlers;
I would use the first type for compile-time advantages, such as knowing
exactly what kind of TCommand is being used in the implementation of my
delegate:
RegisterHandler<ResourceCommand>((command) =>
{
if (command != null)
{
ResourceManager.ResourceReceived(command.ResourceName,
command.ResourceHash, command.ResourceData);
}
});
Inside RegisterHandler, I would now like to do the following:
public void RegisterHandler<TCommand>(CommandHandler<TCommand> handler)
where TCommand : ICommand
{
mCommandHandlers.Add(typeof(TCommand), handler);
}
But I get the following error message:
Error 3 Argument 2: cannot convert from CommandHandler' to 'ICommandHandler'
Why is this? Should the compiler see that in fact my first delegate type
demands the argument to be at least of type ICommand, assuring that the
delegate instance conforms to the signature of the second delegate type as
well?

No comments:

Post a Comment