bob*_*obo 2 c# inheritance constructor design-patterns factory-pattern
我有以下课程:
abstract class Transport{
protected String name;
protected Transport(String name){
this.name=name;
}
protected void DoSomething(){
//Creating some instances of the type of the current instance
}
}
class Bike: Transport {
public Bike(String name): base(name){
}
}
class Bus: Transport {
public Bus(String name): base(name){
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是DoSomething
在Transport
类的方法内创建一些当前实例类型的实例.
我该怎么办呢?
我可以创建一个静态工厂方法,接受我想要创建的子类的名称,然后通过DoSomething
使用方法将它传递给方法中的当前实例的类名this.GetType().Name
.
但这是最好的方法吗?
非常感谢大家.