jeudi 9 juillet 2015

Is using reflection to find type of abstract property a code smell?

So say I have three classes: A, B, and C. A is abstract, B and C inherit from A.

I have created a list of A classes. In a function, I need to know the type of the class I have: A, B, or C. Do I use reflection to get the name? Assign it a type variable and check that? Or am I using abstraction fundamentally wrong?

public abstract class A
{
    public string Type
    {
        get;
        set;
    }
}
public class B : A
{
    public B()
    {
        this.Type = "B";
        Console.WriteLine("I am of type B!");
    }
}
public class C : A
{
    public C()
    {
        this.Type = "C";
        Console.WriteLine("I am of type C!");
    }
}

List<A> listOfStuff = new List<A>();
void doSomething()
{
    listOfStuff.Add(new A());
    listOfStuff.Add(new B());
    listOfStuff.Add(new C());

    foreach (A item in listOfStuff)
    {
        doOperation(item);
    }
}
void doOperation(A thing1)
{
    //Is this bad practice?
    if (thing1.GetType().Name == "B")
    {
        //Do code
    }
    //Or what about this?
    if (thing1.Type == "B")
    {
        //Do code
    }
}





Aucun commentaire:

Enregistrer un commentaire