簡體   English   中英

是否可以從其父類的構造函數返回子類

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

我知道這是行不通的,因為類的構造函數是無效的:

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

有什么辦法做到這一點。

不,沒有辦法,但是...聽起來像是作為靜態方法實現的工廠模式:

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();
    }
}

用法:

var parentClass=  ParentClass.CreateInstance(1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM