协变和逆变行动代表 [英] Covariance and Contravariance for Action Delegates

查看:97
本文介绍了协变和逆变行动代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我卡住了,为什么不是这个工作:

I'm stuck, why isn't this working:

  var childAction = new Action<CancelCommand>(blabla);
  Action<IDomainCommand> upperAction = (Action<IDomainCommand>) childAction;



为什么没有这方面的工作,如果CancelCommand实现IDomainCommand?
顺便说一句:这是合作或逆变什么,我想在这里做什么? ;)

Why isn't this working if CancelCommand implements IDomainCommand? By the way: Is this co or contravariance what i'm trying to do here? ;)

感谢您提前
只求最好
劳林

thank you in advance just the best laurin

修改
谢谢你们的非常快速响应!

EDIT Thank you guys for your very fast responses!

为什么我需要这个是因为我建立一个通用的行动模板的问题。
我有以下接口:

The problem why i need this is because i construct a generic Action Template. I have the following Interface:

IMessageBus.RegisterAction<T>(Action<T> registerAction) where T : IDomainCommand

由于我必须建立在运行时我的代码lookes作为follwing这个动作:

Because i have to build this action on runtime my code lookes as the follwing:

var genericExecuteAction = this.GetType().GetMethod("ExecuteCommandAction",
                                                            BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(commandType);

var actionType = typeof(Action<>).MakeGenericType(commandType);
var @delegate = Delegate.CreateDelegate(actionType, this, genericExecuteAction);
var actionDelegate = (Action<DomainCommandBase>)@delegate;

messageBus.Register(actionDelegate);



问题是我需要转换它,这样我可以把它传递给该方法。
你看到了什么?
,我们使用的是mesasge总线的背后是使用RX,不幸的是所有的方法有使用泛型,还有一个现在没有仿制过载。

The problem is i need to cast it so that i can pass it to this method. You see? Behind the mesasge bus we are using is using RX and unfortunately all the methods there use generics, there a now non-generic-overloads.

推荐答案

动作的类型参数是逆变的:你可以指定一个动作<对象> 来一个动作<字符串方式> 因为很明显,可以在任何物体上工作的方法也可以在一个字符串的工作。

The type parameter of Action is contravariant: you can assign an Action<object> to an Action<string> because obviously a method that can work on any object can also work on a string.

你在这里做的是试图法案,在 CancelCommand (派生型)的工作原理是在任何 IDomainCommand (基本型)。这在逻辑​​上是错误的,所以编译器不会让你这么做 - 如果它这样做,你可以只调用 upperAction 传递一个 DifferentTypeOfDomainCommand

What you do here is trying to bill a method that works on a CancelCommand (derived type) as a method that works on any IDomainCommand (base type). This is logically wrong, so the compiler doesn't let you do it -- if it did, you could just invoke upperAction passing it a DifferentTypeOfDomainCommand.

这篇关于协变和逆变行动代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆