代码之家  ›  专栏  ›  技术社区  ›  Westerlund.io

具有泛型类型的基类,该基类实现具有泛型类型的接口

  •  -1
  • Westerlund.io  · 技术社区  · 7 年前

    FooRepository IEntity Type parameter 'IEntity' hides interface 'IEntity' Cannot resolve symbol 'ID' GetById

    Bar )作为方法,例如 因为它们之间的功能基本相同。

    public abstract class FooRepository<IEntity> : IRepository<IEntity>
    {
        private List<IEntity> _data;
    
        public List<IEntity> GetAll()
        {
            return this._data;
        }
    
        public IEntity GetById(int id)
        {
    
            return this.GetAll().Single(c => c.ID == id);
        }
    }
    
    public class BarRepository : FooRepository<Bar>
    {
    }
    
    public interface IEntity
    {
        int ID { get; set; }
    }
    
    public interface IRepository<IEntity>
    {
        List<IEntity> GetAll();
        IEntity GetById(int id);
    }
    
    public class Bar : IEntity
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Aldert    7 年前

    我使用泛型修复了您的抽象类。

    public abstract class FooRepository<T> : IRepository<T> where T: IEntity
        {
            private List<T> _data;
    
            public List<T> GetAll()
            {
                return this._data;
            }
    
            T IRepository<T>.GetById(int id)
            {
                return this.GetAll().Single(c => c.ID == id);
            }
        }
    
        public class BarRepository : FooRepository<Bar>
        {
        }
    
        public interface IEntity
        {
            int ID { get; set; }
        }
    
        public interface IRepository<T>
        {
            List<T> GetAll();
            T GetById(int id);
        }
    
        public class Bar : IEntity
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }
    

    public abstract class FooRepository<T> where T: IEntity
        {
            private List<T> _data;
    
            public List<T> GetAll()
            {
                return this._data;
            }
    
            T GetById(int id)
            {
                return this.GetAll().Single(c => c.ID == id);
            }
        }
    
        public class BarRepository : FooRepository<Bar>
        {
        }
    
        public interface IEntity
        {
            int ID { get; set; }
        }
    
    
        public class Bar : IEntity
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }