这个类声明:
public abstract class Repository<TE, TD>
where TE : class, IEntity, new()
where TD : DataProvider<TE>
无法通过此类签名实现:
public class SqlRepository<TE> : Repository<TE, SqlDataProvider>
where TE : SqlEntity, new()
在哪里SqlEntity : IEntity
和 SqlDataProvider : DataProvider<SqlEntity>
,我得到这个错误:
Error 1 The type ~ cannot be used as type parameter 'TD' in the generic type or method '~.Repository'. There is no implicit reference conversion from '~.SqlDataProvider' to '~.DataProvider'.
为什么不能把SqlEntity转换成它实现的接口(interface)?
最佳答案
问题是 SqlRepository<TE>
中的内容你正在修理 TD
的内部通用参数,链接到 TE
在Repository<TE, TD>
声明,为SqlEntity
但这不能告诉TE
, 这是通用的。
你能做的就是保持 TD
在 SqlDataProvider
中通用像这样:
public class SqlDataProvider<TD> : DataProvider<TD>
where TD : SqlEntity
然后在 SqlRepository
中显示这种依赖关系像这样:
public class SqlRepository<TE> : Repository<TE, SqlDataProvider<TE>>
where TE : SqlEntity, new()
这会编译,因为 TE
用法一致。
关于c# - 不能继承泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23434006/