bla*_*pea 0 .net c# oop inheritance constructor
我有3个班,ParentClass,ClassA,ClassB.这两个ClassA和ClassB是的子类ParentClass.我想尝试创建类型的对象ClassA或ClassB使用某种枚举来标识类型,然后实例化对象强制转换为父类型.我怎么能动态地做到这一点?请查看下面的代码以及说明的部分//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
{
//.......
}
Run Code Online (Sandbox Code Playgroud)
为什么不呢?
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
{
//.......
}
Run Code Online (Sandbox Code Playgroud)
但是,如果在子类上定义默认构造函数,这会更简单...
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);
}
}
Run Code Online (Sandbox Code Playgroud)