将通用抽象 class 实现到通用接口

Implement generic abstract class to an interface which is generic as well

我有这个摘要class:

public abstract class Entity<T> where T : struct
{
    public T ID { get; set; }
    ... other properties for modify
}

我想做的是在我的 IRepository 中实现这个 class。我试过的是:

public interface IRepository<T> where T : Entity<T> //Entity<T> doesn't make sense here i should use either T2 or what should i do?

我也试着让它像这样工作:

public interface IRepository<T> where T : Entity<object>

实现这一目标的正确方法是什么?

我不确定你想要达到什么目的,但以下是合法的;您的存储库具有与您的实体相同的通用约束 class:

public interface IRepository<T> where T: struct
{
    Entity<T> GetEntityById(int id);
    ...
}

或者下面的方法可行,但我不清楚你想如何使用 T:

public interface IRepository<T,U> where T : Entity<U> where U: struct
{
    Entity<U> GetEntityById(int id);
}

您可以定义以下抽象:

public abstract class Entity<TKey>
    where TKey : struct
{
    public TKey Id { get; set; }
}

public interface IRepository<TEntity, TKey>
    where TEntity : Entity<TKey>
    where TKey : struct
{
    IEnumerable<TEntity> GetAll();
    TEntity GetById(TKey id);
}

然后作为用法,例如:

public class Repository<TEntity, TKey> : IRepository<TEntity, TKey>
    where TEntity : Entity<TKey>
    where TKey : struct
{
    DbContext db;
    public Repository(DbContext db)
    {
        this.db = db;
    }
    public IEnumerable<TEntity> GetAll()
    {
        return db.Set<TEntity>();
    }
    public TEntity GetById(TKey id)
    {
        return db.Set<TEntity>().FirstOrDefault(x => x.Id.Equals(id));
    }
}