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

问题描述

我有3个类, ParentClass ClassA ClassB ClassA ClassB ParentClass 的子类。我想尝试使用某种类型的枚举来创建类型 ClassA ClassB 的对象,然后实例化对象转换为父类型。我如何动态地做到这一点?请看看下面的代码,以及说 //这里放什么的部分。感谢您阅读!

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


$ b b

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

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

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

10-28 21:08