gpt4 book ai didi

c# - 委托(delegate)类型和与通用委托(delegate)类型的协变

转载 作者:行者123 更新时间:2023-12-02 21:52:25 28 4
gpt4 key购买 nike

我想维护一个委托(delegate)列表(此处:“mCommandHandlers”)。由于它们是通用委托(delegate),我实际上定义了第二种类型的委托(delegate),以便我可以维护这样的列表:

public delegate void CommandHandler<TCommand>(TCommand command) where TCommand : ICommand;
public delegate void ICommandHandler(ICommand command);
Dictionary<Type, ICommandHandler> mCommandHandlers;

我会使用第一种类型以获得编译时优势,例如确切地知道在我的委托(delegate)的实现中使用了哪种 TCommand:

RegisterHandler<ResourceCommand>((command) =>
{
if (command != null)
{
ResourceManager.ResourceReceived(command.ResourceName, command.ResourceHash, command.ResourceData);
}
});

在 RegisterHandler 内部,我现在想要执行以下操作:

public void RegisterHandler<TCommand>(CommandHandler<TCommand> handler) where TCommand : ICommand
{
mCommandHandlers.Add(typeof(TCommand), handler);
}

但我收到以下错误消息:

Error 3 Argument 2: cannot convert from CommandHandler<TCommand>' to 'ICommandHandler'

这是为什么呢?编译器是否应该看到实际上我的第一个委托(delegate)类型要求参数至少为 ICommand 类型,以确保委托(delegate)实例也符合第二个委托(delegate)类型的签名?

最佳答案

问题是这两种委托(delegate)类型根本不兼容。为了使这项工作正常进行,您需要添加一个间接层来转换 ICommandTCommand 之间的参数。

public void RegisterHandler<TCommand>(CommandHandler<TCommand> handler)
where TCommand : ICommand
{
mCommandHandlers.Add(
typeof(TCommand),
(command) => handler((TCommand)command);
);
}

关于c# - 委托(delegate)类型和与通用委托(delegate)类型的协变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18345160/

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