【发布时间】: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