具有通用Abstract基类的对象的集合 [英] Collection of objects with common Abstract base class
问题描述
我有一个称为泛型的抽象类,实现如下:
I have an abstract class called generic, implemented as follows:
public abstract class generic
{
public string creatorID { get; set; }
public string itemID { get; set; }
public string name { get; set; }
public DateTime creationDate { get; set; }
public string pageName { get; set; }
...
}
这是通过几个类实现的,例如:
This is implemented through several classes, such as:
public class file : generic
{
public file(string _itemID, string host, string languageReferenceID)
{
DataTable dt = GetRecordsFromDatabase(string _itemID, string host, string languageReferenceID);
if (dt.Rows.Count > 0)
setParameters(dt.Rows[0]);
...
}
private void setParameters(DataRow dr)
{
creatorID = dr["f_MemberID"].ToString();
itemID = dr["f_ID"].ToString();
name = dr["f_Name"].ToString();
creationDate = DateTime.Parse(dr["f_DateCreated"].ToString());
pageName = "files";
...
}
}
我想做的是创建一个抽象抽象类的不同实例的对象列表.这是我正在尝试做的事情:
What I'm trying to do is create a List of objects of different instantiations of that abstract generic class. Here's what I'm attempting to do:
public List<generic> getAlerts(string host, string languageReferenceID)
{
DataTable dt = GetAlertsFromDatabase(host, languageReferenceID);
List<generic> alertList = new List<generic>();
foreach (DataRow dr in dt.Rows)
{
generic g = new generic();
g.itemID = dr["itemID"];
g.description = dr["description"];
g.pageName = dr["pageName"];
g.Add(m);
}
return alertList;
}
现在,这当然会在以下行上引发错误:
Now, of course, this is throwing an error on the line with:
通用g =新的generic();
由于泛型是抽象类,因此无法将其实例化为对象.
Since generic is an abstract class, it can't be instantiated as an object.
我的问题是-考虑到我列出的要求,我如何实现我的目标?我是否应该仅出于实例化泛型类型的列表的目的而创建一个实现抽象类泛型的新类?这对我来说似乎是一个奇怪的解决方案,但这是我现在唯一能想到的.
My question is - how do I accomplish my objective, given the requirements I've listed? Should I create a new class implementing the abstract class generic, for the sole purpose of instantiating lists of type generic? That seems like an odd solution to me, but it's the only thing I can think of right now.
推荐答案
在我看来,这就像 a类工厂.
您需要一个采用 DataRow
,查看其字段并确定应为该行创建 generic
的哪个子类的方法.然后,它创建适当的对象 newObj
,调用 newObj.setParameters(dr)
,并返回 newObj
.
You need a method that takes a DataRow
, looks at its fields, and decides which subclass of generic
should be created for that row. Then it creates the appropriate object newObj
, calls newObj.setParameters(dr)
, and returns newObj
.
最好,实际的工厂方法不采用 DataRow
,而仅采用一个标量值(int,string等)来指示要创建的类型.
Preferably, the actual factory method doesn't take a DataRow
, but rather just the one scalar value (int, string, whatever) that indicates the type to be created.
也许类工厂是通过依赖注入来传递的;您可以对此进行简单或详细说明.
Perhaps the class factory is passed in by dependency injection; you could go simple or elaborate on this.
这篇关于具有通用Abstract基类的对象的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!