【问题标题】:Adding additional constraints to a generic type in function to a class level generic type in C#将附加约束添加到函数中的泛型类型到 C# 中的类级别泛型类型
【发布时间】: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


【解决方案1】:

首先,如果 M 与类的泛型类型 M 相同,则不需要在方法 ReadAll 中将 M 作为泛型类型传递

public List<M> ReadAll()

其次,你需要指定泛型ActiveM是一个类,因为它是GetDbTest方法的一个约束

public List<ActiveM> ReadActiveAll<ActiveM>() where ActiveM : M, class, IActivatable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-21
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    相关资源
    最近更新 更多