mardi 12 mars 2019

Can I create an instance of a derived class based on a certain property defined in my abstract base class?

Basically I have an abstract class with we'll say two properties, one being abstract and some derived classes.

public abstract class BaseClass { 
    public string ID { get; set; } 
    public abstract string Name { get; };
}

public class Class1 : BaseClass { // id would be 1
    public string Name { get { return "Class1 Name"; }
}

public class Class2 : BaseClass {
    public string Name { get { return "Class2 Name"; }
}

public class Class3 : BaseClass {
    public string Name { get { return "Class3 Name"; }
}

Then I have a method in my data layer that returns basically a list of ID's for the base class. What I'm asking is if I can create a new instance of the DerivedClass based on what these ID's are without if or switch statements? So...

List<BaseClass> list = new List<BaseClass>();
string id = dataReader["ID"].ToString(); // say this id = 1
list.Add(new BaseClass { ID = id }); // this would be "Class1 Name" and the Class would be Class1

I know I can't create a new instance of an abstract class so the 'new BaseClass()' doesn't work, but that's the only way I know how to explain it. I've looked into making a copy or clone with Reflection, but not sure if it's actually going to do what I want. This very well might not be possible, but figured I'd ask.





Aucun commentaire:

Enregistrer un commentaire