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

Dan*_*wes 8 c# generics

我正在研究一些协方差/逆变问题,我有一个更广泛的问题,但这一切归结为:

GenericRepository<BaseEntity> repo = new GenericRepository<ProductStyle>(context);
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ell 6

这样做的唯一方法是使用out通用限制(这将使得很难保存对象,但很难检索它们),在interface(不是class)上.如果你有:

interface IGenericRepository<out T> {...}
Run Code Online (Sandbox Code Playgroud)

那么一个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(...) {...}
Run Code Online (Sandbox Code Playgroud)

但请注意,这种协变/ 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
}
Run Code Online (Sandbox Code Playgroud)

  • @DanielDawes只是确保您了解协方差(或相反,相反)所施加的限制. (2认同)