【问题标题】:Having interfaces extend to base abstract class将接口扩展到基本抽象类
【发布时间】:2020-04-19 14:46:46
【问题描述】:

我正在尝试拥有一个基础服务,它具有所有其他服务都继承的通用功能,但遇到了问题并收到以下错误:

Type 'BaseService<Test>' in interface list is not an interface

任何人都可以提出解决此问题的方法吗?或者有更好的方法来解决这个问题?

基础服务

public class BaseService<T> where T : BaseEntity
    {
        private readonly Context _db;
        public BaseService()
        {

        }
        public BaseService(Context db)
        {
            _db = db;
        }
        public async Task<bool> Insert(T entity)
        {
            entity.ModifiedOn = DateTime.UtcNow;
            await _db.Set<T>().AddAsync(entity);
            try
            {
                return await _db.SaveChangesAsync() > 0 ? true : false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }

然后是一个正常的服务,可以访问它,但显示错误

public interface ITestService : BaseService<Test>
    {
    }

【问题讨论】:

  • 接口不能从类继承,只能从其他接口继承。通常你会引入BaseService&lt;T&gt; 实现的接口。并且不要吞下异常,或者使用布尔返回值来指示成功或失败。只需throw 或首先不要catch

标签: c# .net-core interface abstract-class


【解决方案1】:

接口不能从类继承。这里BaseService&lt;T&gt;被定义为一个类。

解决方法是将服务声明为一个类,如下所示:

public class TestService : BaseService<Test>
{
}

【讨论】:

    猜你喜欢
    • 2012-09-22
    • 2013-05-20
    • 2016-12-30
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 2012-05-03
    • 2010-10-21
    • 1970-01-01
    相关资源
    最近更新 更多