Covariance and Contravariance for Action Delegates

前端 未结 4 1159
长发绾君心
长发绾君心 2021-01-27 10:59

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

  var childAction = new Action(blabla);
  Action upperAction = (Action

        
4条回答
  •  囚心锁ツ
    2021-01-27 11:09

    This is contravariance. This isn't working, because if this will be possible, you could write something like this:

    interface IDomainCommand { }
    class CancelCommand : IDomainCommand { }
    class AcceptCommand : IDomainCommand { }
    
            Action a1 = c => { };
            Action a2 = a1;
    
            var acceptCommand = new AcceptCommand();
    
            a2(acceptCommand); // what???
    

    a2 points to a1, and a1 can't accept AcceptCommand argument, because it is not a CancelCommand.

提交回复
热议问题