泛型-使用父类在泛型中指定类型

本文关键字:泛型 类型 父类 | 更新日期: 2023-09-27 18:27:25

我正在研究一些协方差/反方差的东西,我有一个更广泛的问题,但归根结底是:

GenericRepository<BaseEntity> repo = new GenericRepository<ProductStyle>(context);

即使BaseEntity是ProductStyle的父抽象类,这也不起作用,有办法实现吗?

泛型-使用父类在泛型中指定类型

唯一的方法是在interface(而不是class)上使用out通用限制(这将使保存对象变得困难,但检索对象很好)。如果您有:

interface IGenericRepository<out T> {...}

那么IGenericRepository<ProductStyle>可以分配给IGenericRepository<BaseEntity>类型的变量,因为所有的ProductStyle也是BaseEntity,并且我们已经将自己限制为协变/out用法:

IGenericRepository<BaseEntity> tmp = GetRepo<ProductStyle>(context);
// note that the right-hand-side returns IGenericRepository<ProductStyle>
...
private IGenericRepository<T> GetRepo(...) {...}

然而,请注意,这种协变/out的用法使得不可能执行以下操作:

interface IGenericRepository<out T>
{
    T Get(int id); // this is fine, but:
    void Save(T value); // does not compile; this is not covariantly valid
}

我只是想知道这样的东西是否也有用——对GenericRepository的定义使用限制,限制T可以是的基本类型:

void Main()
{
    var repo = new GenericRepository<ProductStyle>(new ProductStyle());
    Console.WriteLine(repo.ToString());  //just output something to make sure it works...
}
// Define other methods and classes here
public class GenericRepository<T> where T : BaseEntity {
    private readonly T _inst;
    public GenericRepository(T inst){
        _inst = inst;
        _inst.DoSomething();
    }
}
public class BaseEntity {
    public Int32 Id {get;set;}
    public virtual void DoSomething() { Console.WriteLine("Hello"); }
}
public class ProductStyle : BaseEntity {
}

因此,如果您有一个GetRepo<T>方法,该方法可以返回一个T的GenericRepository,并且您可以确信TBaseEntity的子级。