首页 > 解决方案 > 对泛型如何与继承一起工作感到困惑

问题描述

我正在尝试在工作中重构一些代码,但遇到了一些问题。假设我有以下代码(为了说明问题而进行了极大简化):

一个抽象的 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>)

我试过的:

  1. 保存所有代码并重新编译
  2. 更改public void InsertToDb()public override void InsertToDb(),在这种情况下,错误消息变为“SpecificDownloader.InsertToDb 找不到合适的方法来覆盖”。
  3. 重新启动 Visual Studio

从理论的角度来看,我认为以上内容应该可以正常工作,但这并没有让我编译,我没有理由这样做。如果我错过了重要的事情,请告诉我。

标签: c#

解决方案


使 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
}

更多关于泛型类型约束


推荐阅读