【发布时间】:2021-11-28 22:00:53
【问题描述】:
考虑下面的代码
public class DrivedDbContext : DbContext
{
public DbSet<M> GetDbSet<M>() where M : class
{
//Returns the DbSet of the Entity type M
}
)
public interface IActivatable
{
Boolean IsActive
{
get;
set;
}
}
public class RepositryBase<M> : IRepository<M> where M : class
{
private DrivedDbContext dbContext = new DrivedDbContext();
public List<M> ReadAll<M>()
{
dbContext.GetDbSet<M>().ToList();
}
public List<ActiveM> ReadActiveAll<ActiveM>() where ActiveM : M, IActivatable
{
dbContext.GetDbSet<ActiveM>().Where(X => X.IsActive).ToList(); // <--- Compiler Error
}
)
以下行显示编译器错误,
dbContext.GetDbSet<ActiveM>().Where(X => X.IsActive).ToList();
CS0452 : ActivM 类型必须是引用类型,才能将其用作方法 DrivedDbContext.GetDbSet() 的泛型类型中的参数 M
我只是想确保用 IActivatable 接口实现的类型 M 只能调用 ReadActiveAll 函数。实现此要求的正确方法是什么?
谢谢
【问题讨论】:
-
你的意思是使用
where Active : class -
请向我们展示我们可以运行以查看您的问题的代码。
标签: c# generics constraints