如何从另一个参数的泛型参数类型推断泛型类型

本文关键字:参数 类型 泛型类型 泛型 另一个 | 更新日期: 2023-09-27 18:32:14

MVC与我的问题无关。不要对这个例子感到困惑。这是一个纯粹的 C# 问题

问题的标题不能很好地解释我认为的问题。


假设,我有一些实体类的基类,称为EntityBase

有些类是这样的

class Entity1 : EntityBase
class Entity2 : EntityBase

我有一个抽象的存储库,可以处理实体上的基本操作。声明是:

abstract class RepositoryBase<TEntity> where TEntity : EntityBase

并且这个类有几个实现

class Repository1 : RepositoryBase<Entity1>
class Repository2 : RepositoryBase<Entity2>

现在有一些带有基础的控制器:

public abstract class RepositoryControllerBase<TRepository, TEntity> 
        where TRepository : RepositoryBase<TEntity>
        where TEntity : EntityBase

实现就像

class Controller1 : RepositoryControllerBase<Repository1, Entity1>
class Controller2 : RepositoryControllerBase<Repository2, Entity2>

现在大家一定已经注意到了,当控制器中的仓库类型为Repository1时,实体类型必须Entity1。否则将是编译错误。

所以,我认为有一种方法可以跳过第二个泛型类型并自动推断该泛型类型。我只是不知道怎么做。有什么建议吗?

也许,如果是Java,这个问题可以很容易地用?解决。将控制器基本声明替换为

public abstract class RepositoryControllerBase<TRepository> 
            where TRepository : RepositoryBase<?>

如何从另一个参数的泛型参数类型推断泛型类型

没有约束类型推断,原因如下:http://blogs.msdn.com/b/ericlippert/archive/2012/03/09/why-not-automatically-infer-constraints.aspx

此外,您的想法的明显反例是使用接口:

interface IEntity1 : IEntityBase {}
interface IEntity2 : IEntityBase {}
interface IRepositoryBase<TEntity> where TEntity : class, IEntityBase {}
class Repository1 : RepositoryBase<IEntity1> {}
class Repository2 : RepositoryBase<IEntity2> {}
class Repository12 : IRepositoryBase<IEntity1>, IRepositoryBase<IEntity2> {}
public abstract class RepositoryControllerBase<TRepository, TEntity> 
    where TRepository : RepositoryBase<TEntity>
    where TEntity : IEntityBase {}
class Controller1 : RepositoryControllerBase<Repository1, Entity1>
class Controller2 : RepositoryControllerBase<Repository2, Entity2>
class Controller12 : RepositoryControllerBase<Repository12, Entity1>

如果不在Controller12定义中指定Entity1类型参数,编译器应检查哪些内容?