How to pass an enum to a parent class's static

2019-08-31 19:13发布

问题:

I have a 3 classes, ParentClass,ClassA,ClassB. Both ClassA and ClassB are subclasses of ParentClass. I wanna try to create objects of type ClassA or ClassB using some kind of enumeration to identify a type, and then instantiate the object cast as the parent type. How can I do that dynamically? Please take a look at the code below, and the parts that say //what do I put here?. Thanks for reading!

enum ClassType
{
    ClassA,
    ClassB
};
public abstract class ParentClass
{


    public ParentClass()
    {
        //....
    }

    public static ParentClass GetNewObjectOfType(ClassType type)
    {
        switch(type)
        {
            case ClassType.ClassA: 
                //What do I put here?
                break;
            case ClassType.ClassB:
                //What do I put here?
                break;
        }

        return null;
    }
}

public class ClassA:ParentClass
{
    //....
}
public class ClassB:ParentClass
{
    //.......
}

回答1:

Why not just this?

public class ParentClass 
{
    public static ParentClass GetNewObjectOfType(ClassType type)
    {
        switch(type)
        {
            case ClassType.ClassA: 
                return new ClassA();
                break;
            case ClassType.ClassB:
                return new ClassB();
                break;
        }

        return null;
    }
}

public class ClassA:ParentClass
{
    //....
}
public class ClassB:ParentClass
{
    //.......
}

But, if you define default constructors on your subclasses, this is a lot simpler...

public class ParentClass 
{
    private static Dictionary<ClassType, Type> typesToCreate = ...

    // Generics are cool
    public static T GetNewObjectOfType<T>() where T : ParentClass
    {
        return (T)GetNewObjectOfType(typeof(T));
    }

    // Enums are fine too
    public static ParentClass GetNewObjectOfType(ClassType type)
    {
        return GetNewObjectOfType(typesToCreate[type]);
    }

    // Most direct way to do this
    public static ParentClass GetNewObjectOfType(Type type)
    {
        return Activator.CreateInstance(type);
    }
}