我有以下类定义:

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);
     }
}


为什么这会抱怨不能将Action<TDerivedThing>分配给Action<IThing>,我应该如何解决呢?

最佳答案

当然不是,即使EventArgs是对象,也不能将List<EventArgs>分配给List<object>

 public void Register<TDerivedThing>(Action<TDerivedThing> thingAction)
      where TDerivedThing : IThing
 {
    _thingActions.Add(t => thingAction(t as TDerivedThing));
 }


可能是一个解决方案,但我不知道您的应用程序。

09-25 21:50