将泛型抽象类实现到泛型接口



我有这个抽象类:

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

我正在尝试做的是在我的独立中实现这个类。 我尝试的是:

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>

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

我不确定您要实现什么,但以下内容是合法的;您的存储库与实体类具有相同的通用约束:

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));
    }
}

最新更新