【发布时间】:2019-12-04 14:30:12
【问题描述】:
大家好, 所以我只想使用泛型和强制转换。但是由于某种原因不起作用,我不知道为什么。
abstract class BaseModel {}
class NewModel : BaseModel {}
class BaseRepo<T> where T : BaseModel {}
class NewRepo : BaseRepo<NewModel> {}
class Test
{
public void TestMethod()
{
BaseRepo<BaseModel> t1 = new BaseRepo<BaseModel>();
BaseRepo<NewModel> t2 = new NewRepo();
BaseRepo<BaseModel> t3 = new BaseRepo<NewModel>();
// Cannot convert initializer type 'TestGeneric.BaseRepo<TestGeneric.NewModel> to target type 'TestGeneric.BaseRepo<BaseModel>'.
// Cannot implicitly convert type 'TestGeneric.BaseRepo<TestGeneric.NewModel>' to 'TestGeneric.BaseRepo<TestGeneric.BaseModel>'.
// Type 'NewModel' doesn't match expected type 'BaseModel'.
// Cannot convert source type 'TestGeneric.BaseRepo<TestGeneric.NewModel>' to target type 'TestGeneric.BaseRepo<TestGeneric.BaseModel>'.
BaseRepo<BaseModel> t4 = new NewRepo();
// Cannot convert initializer type 'TestGeneric.BaseRepo<TestGeneric.NewModel> to target type 'TestGeneric.BaseRepo<BaseModel>'.
// Cannot implicitly convert type 'TestGeneric.NewRepo' to 'TestGeneric.BaseRepo<TestGeneric.BaseModel>'.
// Cannot convert source type 'TestGeneric.NewRepo' to target type 'TestGeneric.BaseRepo<TestGeneric.BaseModel>'.
}
}
我只是不明白为什么 t3 和 t4 抛出异常同时 t1 和 t2 工作。甚至 NewModel 是 BaseModel 的子类,最后两个不起作用。
【问题讨论】:
-
检查副本 - 特别是我的 answer。我认为这很容易理解。
标签: c# generics .net-core types