Reputation: 806
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.
Upvotes: 0
Views: 268
Reputation: 37059
To me, this looks like a class factory.
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
.
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.
Upvotes: 2