“哪里”通用约束限制?

时间:2015-11-28 20:41:11

标签: c# .net generics

我如何实现以下示例?

public interface IRepositoryFactory
{
    TRepository Create<TRepository>(DbContext context) where TRepository : IRepository<*anything derived from EntityBase*>;
}

我希望能够实现以下目标。

public interface IUserRepository : IRepository<User>
{        
}

var repository = factory.Create<IUserRepository>(context);

1 个答案:

答案 0 :(得分:3)

只需添加另一个泛型类型并赋予其类型约束:

public interface IRepositoryFactory
{
    TRepository Create<TRepository, TEntity>(DbContext context) 
        where TRepository : IRepository<TEntity>
        where TEntity : EntityBase;
}