C# 在列表中添加模板类

本文关键字:添加 列表 | 更新日期: 2023-09-27 18:35:29

我有这样的类

国家存储库

public class CountryRepository : BaseRepository<Country>

哪里

基本存储库

public abstract class BaseRepository<DT> : IRepository<DT>
    where DT : IDomainEntity

独立

public interface IRepository<DT>
    where DT : IDomainEntity

我想将类存储在这样的列表中

this.Repositories = new List<BaseRepository<IDomainEntity>>();
var o = new CountryRepository();
this.Repositories.Add(o);

错误 4 参数 1:无法从"国家/地区存储库"转换为 "基本存储库"

它不起作用,我哪里出错了。

C# 在列表中添加模板类

我哪里错了

CountryRepository派生自与List预期的BaseRepository<IDomainEntity>类型不兼容的赋值BaseRepository<Country>

以下是修复方法:

选项 1:将非泛型抽象类设置为类层次结构的根,并从中派生泛型类。

public abstract class BaseRepository
public abstract class BaseRepository<DT>: BaseRepository, IRepository<DT>
   where DT: IDomainEntity
public class CountryRepository: BaseRepository<Country>

this.Repositories = new List<BaseRepository>();
var o = new CountryRepository();
this.Repositories.Add(o);

选项 2:接口协方差。如果 DT 仅用作输出参数类型、方法返回类型或声明中的只读属性类型IRepository它将起作用。

public interface IRepository<out DT> where DT: IDomainEntity
public abstract class BaseRepository<DT> : IRepository<DT>
  where DT : IDomainEntity
public class CountryRepository : BaseRepository<Country>
// Note the usage of IRepository<IDomainEntity>, not BaseRepository 
this.Repositories = new List<IRepository<IDomainEntity>>();   
var o = new CountryRepository();
this.Repositories.Add(o);

两者之间有区别

BaseRepository<Country> 

和基本存储库。

您的国家/地区存储库派生自

BaseRepository<Country> 

而不是来自 BaseRepository,因此您会收到错误。

分配继承权:

public class CountryRepository : BaseRepository