c# - 对泛型如何与继承一起工作感到困惑
问题描述
我正在尝试在工作中重构一些代码,但遇到了一些问题。假设我有以下代码(为了说明问题而进行了极大简化):
一个抽象的 Row 类:
abstract class Row
{
}
扩展 Row 的具体 Row 类
class SpecificRow : Row
{
}
采用泛型类型和接受 ICollection 的方法的接口:
interface IDbInsertable<T>
{
void InsertToDb(ICollection<T> list);
}
实现上述接口的抽象类:
abstract class BaseDownloader: IDbInsertable<Row>
{
public abstract void InsertToDb(ICollection<Row> list);
//and other unrelated methods...
}
扩展 BaseDownloader 的具体类:
class SpecificDownloader : BaseDownloader
{
public void InsertToDb(ICollection<SpecificRow> list)
{
//implementation
}
//other stuff
}
在SpecificDownloader 类中,我收到错误“SpecificDownloader 没有实现继承的抽象成员BaseDownloader.InsertToDb(ICollection<Row>)
”
我试过的:
- 保存所有代码并重新编译
- 更改
public void InsertToDb()
为public override void InsertToDb()
,在这种情况下,错误消息变为“SpecificDownloader.InsertToDb 找不到合适的方法来覆盖”。 - 重新启动 Visual Studio
从理论的角度来看,我认为以上内容应该可以正常工作,但这并没有让我编译,我没有理由这样做。如果我错过了重要的事情,请告诉我。
解决方案
使 BaseDownloader 成为一个泛型类。并添加一个强制 T 成为行类型的类型约束。像这样
//Class implements the interface and uses the Generic type T from basedownloader. And that has the type constraint
abstract class BaseDownloader<T> : IDbInsertable<T> where T : Row
{
//This forces T to always be a type row
public abstract void InsertToDb(ICollection<T> list);
//and other unrelated methods...
}
然后在从 basedownloader 继承时指定您想要的行类型。像这样
//Class now gives specificrow as the generic type when inheriting from basedownloader
class SpecificDownloader : BaseDownloader<SpecificRow>
{
//Now InsertToDb has a collection of SpecificRow instead of just row
public override void InsertToDb(ICollection<SpecificRow> list)
{
//implementation
}
//other stuff
}
更多关于泛型类型约束
推荐阅读
- deep-linking - 使用同一域配置托管和深度链接 - Branch.io
- php - 在 10 月 CMS 中从事件插件 php 渲染部分内容
- apache-kafka - 仅允许来自某些主机/IP 的消费者访问 kafka 主题
- r - library(tidyverse) 提供以前从未见过的错误消息
- android - 菜单在中心而不是被触摸的地方弹出
- c++ - 当我尝试添加 zext 和调用指令时,LLVM Pass 崩溃
- flutter - ListView Builder 在初始化器中只能访问静态成员
- python-3.x - 存储在列表中时,函数总是缺少 1 个必需的位置参数
- html - 如何解决 WebGL Unity 游戏中的此错误?
- bootstrap-4 - 即使表单有效,formvalidation.io 也会阻止表单提交