【问题标题】:C# Abstract Class InstanitiationC# 抽象类实例化
【发布时间】:2017-03-11 17:32:15
【问题描述】:

我发现我的服务类总是有一个模式,所以我想要一个抽象类。但是我想在抽象类内部实现一些基础方法,每个继承这个抽象类的子类都有自己的repo类,如何在这个抽象类内部实现一个新的泛型repo?例如,我可以在抽象类中创建一个构造函数来用数据初始化这个 EList,这样我就可以写更少的代码。

下面的抽象类:

public abstract class ServiceBase<TEntity,TModel> : IService<TModel>
{
    protected internal abstract List<TEntity> EList { get; }

    public long Create(TModel entity)
    {

    }

    public long Delete(int id)
    {
        throw new NotImplementedException();
    }

    public TModel Read(int id)
    {
        throw new NotImplementedException();
    }

    public long Update(TModel entity)
    {
        throw new NotImplementedException();
    }
}

假设抽象类中的所有方法都需要使用这个通用的Repo类,并且这个Repo类将在每个子类中定义,如果我将TRepo放在公共抽象类ServiceBase中,TRepo会被声明为一个新实例在子班还是有更好的实现?


子类之一

public class ItemModifierService : ServiceBase<ItemModifierEntity, ItemModifierModel>
{
    private ItemModifierRepository IMRepo = new ItemModifierRepository();

    private List<ItemModifierEntity> IMEList = new List<ItemModifierEntity>();

    public ItemModifierService()
    {
        IMEList = IMRepo.Read(false);
    }


    public ItemModifierModel Read()
    {

    }

    public ItemModifierModel Read(int id)
    {

    }

    public long Create(ItemModifierModel entity)
    {

    }

    public long Update(ItemModifierModel entity)
    {

    }

    public long Delete(int id)
    {

    }

    public bool Exist(int id)
    {
        return IMEList.Any(x => x.id == id);
    }
}

如何转换这个构造函数

public ItemModifierService()
{
    IMEList = IMRepo.Read(false);
}

到通用类中并在抽象类中实现它,这样我就不必在每个子类中编写更多代码或在子类中使用更多自定义代码行来扩展此构造函数?

先谢谢大家了。

祝你有美好的一天。

【问题讨论】:

  • 您真的希望在基类中有一个列表,在派生类中也有一个吗?至于如何在抽象类中编写构造函数:与在具体类中的方式完全相同...
  • @Jon Skeet,感谢您的评论,是的,因为通常所有服务类都使用 repo 类从数据库中拥有自己的对象实体列表。列表可以是通用类型,也可以是 repo,我只会在子类中定义它,这样我相信在编码方面会更有效率。

标签: c# .net inheritance


【解决方案1】:

不了解问题领域的最简单方法是在派生类中创建一个实例并将其传递给基类中的通用属性,如下所示:

public interface IRepo<Item> {
    public List<Item> Read(bool arg);
}

public abstract class ServiceBase<TEntity,TModel, TRepo> : IService<TModel> where TRepo : IRepo<TEntity>
{
    protected internal abstract List<TEntity> EList { get; private set; }
    protected internal TRepo repo { get; private set; };

    public ServiceBase(TRepo instance)
    {
        this.repo = instance;
        this.EList = this.repo.Read(false);
    }
}

public class ItemModifierService : ServiceBase<ItemModifierEntity, ItemModifierModel, ItemModifierRepository> {
    public ItemModifierService() : base(new ItemModifierRepository()) {
    }
}

【讨论】:

  • 感谢您的代码,我可以知道为什么我必须将 TRepo 传递给抽象类中的构造函数吗?我可以将这个 TRepo 实例用于子类中的所有其他方法吗?
  • 你传递它是因为抽象类不知道如何初始化 Repository 对象,例如你的 Item repo 可能需要一些参数在它的构造函数中,像这样:new ItemModifierRepository(someArgument)。至于第二部分 - 是的,protected 意味着您将能够在所有子类中访问此属性。我已经编辑了代码使repo 有一个private set 所以只有抽象类可以设置它,但所有子类都可以使用它
猜你喜欢
  • 2016-09-21
  • 2012-09-08
  • 1970-01-01
  • 2020-04-29
  • 1970-01-01
  • 2013-10-31
  • 1970-01-01
  • 2017-02-05
相关资源
最近更新 更多