问题
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
{
//.......
}
回答1:
Why not just this?
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);
}
}
来源:https://stackoverflow.com/questions/14990906/how-to-pass-an-enum-to-a-parent-classs-static-function-to-instantiate-a-child-c