如何将枚举传递给父类的静态函数以实例化子类? [英] How to pass an enum to a parent class's static function to instantiate a child class?
问题描述
我有 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
{
//.......
}
但是,如果您在子类上定义默认构造函数,这会简单得多...
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屋!