作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想维护一个委托(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)类型根本不兼容。为了使这项工作正常进行,您需要添加一个间接层来转换 ICommand
和 TCommand
之间的参数。
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/
COW 不是奶牛,是 Copy-On-Write 的缩写,这是一种是复制但也不完全是复制的技术。 一般来说复制就是创建出完全相同的两份,两份是独立的: 但是,有的时候复制这件事没多大必要
我是一名优秀的程序员,十分优秀!