在父类的方法中创建子类的一些实例
我有以下类:
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){
}
}
我想要做的是在 Transport
类的 DoSomething
方法中创建当前实例类型的一些实例。
我该怎么办呢?
我可以创建一个静态工厂方法,它接受我想要创建的子类的名称,然后使用 this.GetType 在
。DoSomething
方法中将当前实例的类名称传递给它().名称
但这是最好的方法吗?
非常感谢大家。
I have the following classes:
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){
}
}
What I would like to do is to create some instances of the type of the current instance inside the DoSomething
method of the Transport
class.
How would I go about it?
I can create a static factory method that accepts the name of the child class I would like to create and then pass it the class name of the current instance inside the DoSomething
method by using this.GetType().Name
.
But is this the best way?
Many thanks to you all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在基类中制作
受保护的抽象传输创建(字符串名称)
方法,并在派生的类中覆盖它以调用其构造函数。You can make a
protected abstract Transport CreateNew(string name)
method in the base class, and override it in the derived classes to call their constructors.您愿意使用反射吗?
以上适用于您的具体情况。请注意使用 [0] 来获取第一个构造函数。对于您问题中的小例子来说,这不是问题。您可以考虑在 System.Type 上使用其他重载来获取您想要的特定构造函数。
Are you open to using reflection?
The above works in your specific case. Note the use of [0] to get the first constructor. This is a non-issue for the trivial example in your question. You might consider using other overloads on System.Type to get the specific constructor that you want.