0

我有 3 节课,ParentClass, ClassA, ClassB. ClassA和都是ClassB的子类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
{
    //.......
}
4

1 回答 1

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);
    }
}
于 2013-02-20T22:11:31.517 回答