简体   繁体   中英

Is it possible to return a child class from the constructor of its parent class

I know this doesn't work this way, since the constructor of a class is a void:

class ParentClass
{
    public ParentClass(int case)
    {
       if(case==1) 
           return new ChildClass1();
       else 
           return new ChildClass2();
    }
}

Is there any way of doing this.

No, there is no way but... It sounds like a factory pattern implemented as static method:

class ParentClass
{ 
    // "disable" ctor for public use but 
    // allow for children
    protected ParentClass() { }

    public static ParentClass CreateInstance(int @case)
    {
       if(@case==1) 
           return new ChildClass1();
       else 
           return new ChildClass2();
    }
}

Usage:

var parentClass=  ParentClass.CreateInstance(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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