我目前正在开始一个新项目,但遇到了一些阅读障碍。我希望有人能帮助我,我会尽力描述问题。
我有一个名为“EntityBase”的基本抽象类。从这个类中有大约 100 个左右的继承类。 EntityBase 有许多方法,例如 Load() 和 Save(),它们对我所有的继承类都是通用的。它还有几个接受整数或 IDataReader 的构造函数,用于从数据库加载对象。
一切都很好。
输入我的新基类,名为 EntityCollectionBase,它扩展了 List
public bool Load()
{
bool result = true;
using (IDataReader reader = _dbManager.ExectureReaderSProc(this.LoadProcedure, new SqlParameter[] { new SqlParameter("@parentId", _parentID) }))
{
this.Add(new EntityBase(reader)); // WON'T WORK, EntityBase IS ABSTRACT
}
return result;
}
如您所见,我需要 Load 函数以通用方式处理任何扩展 EntityBase 的内容,但因为 EntityBase 是抽象的,所以我无法实例化它。
有什么想法吗?
谢谢,
桑尼
最佳答案
每当您根据运行时数据创建多个可能类之一的实例时,工厂就是答案:
public interface IEntityFactory
{
EntityBase CreateEntity(IDataReader reader);
}
您将修改加载类以接受一个:
private readonly IEntityFactory _entityFactory;
public Loader(IEntityFactory entityFactory)
{
_entityFactory = entityFactory;
}
然后您将在 Load
方法中使用工厂:
public void Load()
{
using(var reader = _dbManager.ExectureReaderSProc(this.LoadProcedure, new SqlParameter[] { new SqlParameter("@parentId", _parentID) }))
{
Add(_entityFactory.CreateEntity(reader));
}
}
关于c# - 使用适用于所有继承对象的方法为基类型创建集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3346961/