简体   繁体   English

C#-在抽象超类中生成相同类型的新具体类

[英]C# - Generate a new concrete class of the same Type in abstract super class

I have an abstract base class with for example two subclasses. 我有一个带有两个子类的抽象基类。 In the abstract class I use the template pattern in the "real world" but for this example lets say I have a generator method which returns the type AbstractBaseClass . 在抽象类中,我在“真实世界”中使用模板模式,但对于本示例,我有一个生成器方法,该方法返回类型AbstractBaseClass Now I want the instance to be the concrete type at runtime. 现在,我希望实例在运行时成为具体类型。 This is important for the template pattern as I use different implementations and hooks in each subclass. 这对于模板模式很重要,因为我在每个子类中使用不同的实现和挂钩。

For now I came up with the following pseudo code. 现在,我想出了以下伪代码。 I check whether this is a concrete class and call the constructor of either one of the subclasses and return the new Instance. 我检查是否一个具体的类,并调用任一子类的构造函数并返回新的Instance。

public abstract class AbstractBaseClass
{
    private string _someString1;
    private string _someString2;

    protected AbstractBaseClass(string someString1, string someString2)
    {
        _someString1 = someString1;
        _someString2 = someString2;
    }

    public AbstractBaseClass GenerateClass()
    {
        //...

        if(this is SubClass1)
        {
            return new SubClass1("Foo1", "Foo2");
        }

        if(this is SubClass2)
        {
            return new SubClass2("Foo3", "Foo4");
        }
        return null;
    }

    // more methods
}

public class SubClass1 : AbstractBaseClass
{
    public SubClass1(string someString1, string someString2) : base(someString1, someString2)
    { }

    // more methods
}

public class SubClass2 : AbstractBaseClass
{
    public SubClass2(string someString1, string someString2) : base(someString1, someString2)
    { }

    // more methods
}

So far so good. 到现在为止还挺好。 But now I want my code to be open for extensions but closed for modifications . 但是现在我希望我的代码对扩展开放,而对修改开放 I want to be able to add as many subclasses as I want, but don't have to change the generator method. 我希望能够添加任意数量的子类,但不必更改generator方法。 How can this be achieved? 如何做到这一点?

So it gets decided at runtime which instance to create. 因此,它在运行时决定要创建哪个实例。 Keep in mind that I don't have an empty constructor. 请记住,我没有空的构造函数。 But there is in every case a constructor with the same signature. 但是在每种情况下,都有一个具有相同签名的构造函数。

I found this post. 我发现了这篇文章。 It seems to go this direction but it didn't really helped me: 似乎朝这个方向发展,但并没有真正帮助我:

Thanks! 谢谢!

you should use the Factory Pattern here : 您应该在此处使用工厂模式

Define an interface for creating an object, but let subclasses decide which class to instantiate. 定义用于创建对象的接口,但让子类决定实例化哪个类。 The Factory method lets a class defer instantiation it uses to subclasses. Factory方法允许类延迟其用于子类的实例化。

for example, though not fully qualified as Factory pattern, take a look at this snippet: 例如,尽管没有完全符合Factory模式的条件,但请查看以下代码段:

public abstract class A
{
 // Some abstract stuff

 public static A CreateInstance(Type myType)
 {
   Type type = myType; // pseudo method
   return (A)Activator.CreateInstance(type);  
 }
}

you can initialize all of your subclasses in one method. 您可以使用一种方法初始化所有子类。

I advice you to look deeper into Abstract Factory Design Pattern In C# in order to learn and understand the concept better. 我建议您更深入地研究C#中的“ 抽象工厂设计模式” ,以便更好地学习和理解该概念。

Edit: 编辑:


Or as suggested by the comment for a better generic solution: 或如评论所建议的那样,可以提供更好的通用解决方案:

public abstract class A
{
  // Some abstract stuff

  public static A CreateInstance<T>() where T : A, new() => new T();
}

try this : 尝试这个 :

public AbstractBaseClass GenerateClass()
{

    return (AbstractBaseClass) Activator.CreateInstance(this.GetType(), StringParametter1,StringParametter2);
}

Good luck ! 祝好运 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM