【问题标题】:Can't access functions in base generic class无法访问基本泛型类中的函数
【发布时间】:2012-02-04 05:06:12
【问题描述】:

我有一个带有服务引用的通用抽象基类。当我尝试从具体实现类访问任何属性时,我收到以下错误。 “存储库”不包含“添加”的定义,并且找不到接受“存储库”类型的第一个参数的扩展方法“添加”(您是否缺少 using 指令或程序集引用?)

**Base class**
namespace Services
{
    public abstract class BaseRepository<T> : IRepository<T>
    {
        public IService<T> _serviceContext;

        public BaseRepository(IService<T> serviceContext)
        {
            _serviceContext = serviceContext;
        }

        #region IRepository<T> Members

        public List<T> GetAll()
        {
            return _serviceContext.GetAll();
        }

        public T GetById(Guid id)
        {
            throw new NotImplementedException();
        }

        public void Add(T entity)
        {
            _serviceContext.Add(entity);
        }

        public void Remove(T entity)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

**Concrete class**
namespace Services
{
    public class SpecialRepository : BaseRepository<SpecialItem>, ISpecialRepository
    {
        public SpecialRepository() : base(new DataAccess.SpecialList()) 
        {
        }
    }
}

**Service Class**
namespace DataAccess
{ 
    public class SpecialList : IService<SpecialItem>
    {
        public List<SpecialItem> GetAll()
        {
            //Implementation 
        }
    }
} 

**Repository Interface**
namespace Domain
{
    public interface IRepository<T>
    {
        List<T> GetAll();
        T GetById(Guid id);
        void Add(T entity);
        void Remove(T entity);
    }
}

**Service Interface**
namespace DataAccess
{
    public interface IService<T>
    {
        List<T> GetAll();
        void Add(T entity);
    }
}

感谢任何帮助。提前致谢!

【问题讨论】:

  • Repository 类在哪里?这是您的错误中提到的类名,但您的代码中没有这样的类。
  • 我看到的唯一问题是您没有在 SpecialList 中实现 Add,即使它继承的接口具有 Add 函数。
  • 谢谢伙计们,你们为我指明了正确的方向……我正在编程的界面对存储库的引用被注释掉了。公共接口 ISpecialRepository //: IRepository { }

标签: c# generics


【解决方案1】:

您需要在 SpecialList 中定义一个 Add 方法。

我添加了一个,但调用时没有出错

 SpecialRepository rep = new SpecialRepository();
 rep.Add(new SpecialItem());

【讨论】:

  • 感谢您的帮助。见上面的评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
  • 2020-06-01
  • 2016-06-23
  • 2022-03-18
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
相关资源
最近更新 更多