创建父类的构造子对象 [英] Create child object in parent constructor
问题描述
是否有可能创建一个使用父类的构造,并通过它的一些各种参数(一个字符串,在这种情况下)的子对象,告诉它应该创建子类型?实例
Is it possible to create an instance of a child object using the parent's constructor and passing it some kind of parameter (a string, in this case) to tell it the type of child that should be created?
推荐答案
没有。在C#中,创建一个类的实例,然后的运行时调用它的构造。通过构造函数执行为时已晚来接其他类型的时间。
No. In C#, you create an instance of a class, then the runtime calls its constructor. By the time the constructor executes it's too late to pick another type.
然而,派生类的构造函数总是调用基类的一个人的构造函数,并且可以使用那你的优势(避免重复的代码)。
However, a derived class' constructor always calls one of its base class' constructors, and you can use that to your advantage (to avoid repeating code).
人们常常创建的工厂,以你在说什么。例如,给定的类父
, Child1:家长
和 CHILD2:家长
,可以编写一个工厂是这样的:
People often create factories to do what you're talking about. For example, given the classes Parent
, Child1:Parent
, and Child2:Parent
, you might write a factory like this:
public class ParentFactory {
public Parent CreateParent(string type) {
switch(type) {
case "Child1":
return new Child1();
case "Child2":
return new Child2();
default:
throw new ArgumentException("Unexpected type");
}
}
}
这篇关于创建父类的构造子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!