无法将儿童通用类型转换为父类型

时间:2018-08-24 14:18:39

标签: c# generics inheritance covariance

这是我正在使用的结构:

public class BaseModel{}

public class ChildModel1: BaseModel {}

public class ChildModel2: BaseModel {}


class BaseExecutor<T> where T: BaseModel {}

class ChildExecutor1: BaseExecutor<ChildModel1> {}

class ChildExecutor2: BaseExecutor<ChildModel2> {}

以下方法会产生设计时错误

  

无法将类型'ChildExecutor1'隐式转换为'BaseExecutor'

private BaseExecutor<BaseModel> GetExecutor(int executorId)
{
    if(executorId == 1) {
        return new ChildExecutor1();
    }
    else {
        return new ChildExecutor2();
    }
}

如何解决此问题?

0 个答案:

没有答案