[英]Is it possible to return a child class from the constructor of its parent class
I know this doesn't work this way, since the constructor of a class is a void: 我知道这是行不通的,因为类的构造函数是无效的:
class ParentClass
{
public ParentClass(int case)
{
if(case==1)
return new ChildClass1();
else
return new ChildClass2();
}
}
Is there any way of doing this. 有什么办法做到这一点。
No, there is no way but... It sounds like a factory pattern implemented as static method: 不,没有办法,但是...听起来像是作为静态方法实现的工厂模式:
class ParentClass
{
// "disable" ctor for public use but
// allow for children
protected ParentClass() { }
public static ParentClass CreateInstance(int @case)
{
if(@case==1)
return new ChildClass1();
else
return new ChildClass2();
}
}
Usage: 用法:
var parentClass= ParentClass.CreateInstance(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.