为什么泛型看不到我的继承
本文关键字:继承 我的 看不到 泛型 为什么 | 更新日期: 2023-09-27 18:37:19
这是我正在使用的代码,它在实例化时出现构建错误。 我不确定为什么没有看到我的 SpecialHandler 类型为 BaseHandler,T 设置为 SpecialEntity
static class HandlerFactory
{
public static BaseHandler<BaseEntity> Create(string typeString)
{
throw new NotImplementedException();
}
public static BaseHandler<T> Create<T>(string typeString ) where T : BaseEntity {
if (typeString == "Special")
**return new SpecialHandler();** //THERE'S BUILD ERROR HERE EVEN THOUGH Special Handler is inherits from type BaseHandler<T>
else
return null;
}
}
public class BaseHandler<T> where T : BaseEntity
{
public T GetEntity()
{
throw new NotImplementedException();
}
}
public class SpecialHandler : BaseHandler<SpecialEntity> {}
public class BaseEntity{}
public class SpecialEntity : BaseEntity{}
(使用我的心理调试技能来推断问题)
除非指定(无论如何,它仅适用于接口),否则遗传参数是不变的,即精确。
定义为List<Mammal>
的集合与定义为List<Animal>
的集合或定义为List<Cat>
的集合没有任何关系。
Create
方法说它返回一个BaseHandler<BaseEntity>
,而不是一个BaseHandler<SpecialEntity>
,你的SpecialHandler
是-一个BaseHandler<SpecialEntity>
,但它不是一个BaseHandler<BaseEntity>
。