【问题标题】:Creating some instances of the child class in a method of the parent class在父类的方法中创建子类的一些实例
【发布时间】:2011-07-28 11:37:42
【问题描述】:

我有以下课程:

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().NameDoSomething 方法内的当前实例的类名传递给它。

但这是最好的方法吗?

非常感谢大家。

【问题讨论】:

    标签: c# design-patterns inheritance constructor factory-pattern


    【解决方案1】:

    您可以在基类中创建protected abstract Transport CreateNew(string name) 方法,并在派生类中重写它以调用其构造函数。

    【讨论】:

      【解决方案2】:

      你愿意使用反射吗?

      protected void DoSomething(){
          Transport newOne =  GetType()
                                 .GetConstructors()[0]
                                 .Invoke(new[] {"some name"})
      }
      

      以上适用于您的具体情况。注意使用 [0] 来获取第一个构造函数。对于您问题中的简单示例,这不是问题。您可以考虑在 System.Type 上使用其他重载来获取您想要的特定构造函数。

      【讨论】:

      • 或使用Activator.CreateInstance。请注意,这会慢得多。
      猜你喜欢
      • 2021-08-28
      • 2021-10-29
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      相关资源
      最近更新 更多