c# - 不能继承泛型

标签 c# generics

这个类声明:

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 : IEntitySqlDataProvider : 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的内部通用参数,链接到 TERepository<TE, TD>声明,为SqlEntity但这不能告诉TE , 这是通用的。

你能做的就是保持 TDSqlDataProvider 中通用像这样:

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/

相关文章:

c# - Caliburn.Micro WindowManager找不到 View

c# - 在另一个列表中添加列表项

java - 使用通配符时 Java Hashmap 的返回类型

java - 何时在 Java 泛型中使用通配符?

java - 为什么在泛型类(Java)的构造函数中提供类型参数是错误的?

c# - 访问所有 Windows 用户的应用程序数据文件夹路径

c# - File.Copy 方法使文件无法访问

c# - 没有提供种子时随机播种的是什么类?

json - 使用Gson库动态解析未知数据

java - 泛型转换问题