如何将枚举传递给父类的静态函数以实例化子类? [英] How to pass an enum to a parent class's static function to instantiate a child class?

查看:60
本文介绍了如何将枚举传递给父类的静态函数以实例化子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个班级,ParentClassClassAClassB.ClassAClassB 都是 ParentClass 的子类.我想尝试使用某种枚举来标识类型来创建 ClassAClassB 类型的对象,然后将对象实例化为父类型.我怎样才能动态地做到这一点?请看一下下面的代码,以及说//我在这里放什么?的部分.感谢阅读!

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

推荐答案

为什么不只是这个?

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

这篇关于如何将枚举传递给父类的静态函数以实例化子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆