无法将Action <TDerivedThing>分配给Action <IThing>

Bla*_*keH 2 c#

我有以下类定义:

public class Registry
{
     private List<Action<IThing>> _thingActions = new List<Action<IThing>>();

     public Register<TDerivedThing>(Action<TDerivedThing> thingAction)
          where TDerivedThing : IThing
     {
        // this line causes compilation issue
        _thingActions.Add(thingAction);
     }     
}
Run Code Online (Sandbox Code Playgroud)

为什么会出现这种抱怨它不能分配Action<TDerivedThing>Action<IThing>了,我应该如何去解决呢?

mil*_*ose 7

如果C#允许你这样做,这样的代码将是有效的:

interface IFruit {
    void Eat();
}

class Apple : IFruit {
    // ...
    void EatApple();
}

class Pear : IFruit {
    // ...
    void EatPear();
}

void EatApple(Apple a) {
    a.EatApple();
}

void EatPear(Pear p) {
    p.EatPear();
}

Action<IFruit> fruitAction = EatApple;
fruitAction(new Pear()); // Calls EatApple(new Pear())
Run Code Online (Sandbox Code Playgroud)

演员表是无效的,因为它不应该是,你不应该首先尝试这样做.您的IThing行动清单都必须是接受任何水果的行动.