具有公共抽象基类的对象集合 [英] 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:
generic g = new 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类工厂.
To me, this looks like a class factory.
您需要一个方法,它接受一个 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.
这篇关于具有公共抽象基类的对象集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!