如何将枚举传递给父类的静态函数来实例化子类?

时间:2013-02-20 22:09:25

标签: c# .net oop inheritance constructor

我有3个班级,ParentClassClassAClassBClassAClassB都是ParentClass的子类。我想尝试使用某种枚举来创建ClassAClassB类型的对象来标识类型,然后将对象强制转换为父类型。我怎么能动态地做到这一点?请查看下面的代码以及说//what do I put here?的部分。谢谢你的阅读!

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 个答案:

答案 0 :(得分:6)

为什么不呢?

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
{
    //.......
}

但是,如果你在子类上定义默认构造函数,这就简单了很多......

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);
    }
}