2014-11-05 129 views
-1

我有一個父類和很多兒童類:如何覆蓋方法返回類型?

public class ParentViewModel 
{ 
    public int Id{set;get;} 
    public string Name{set;get;} 
    <..and another 10 properties..> 
} 

public class ChildViewModel_1:ParentViewModel 
{ 
    public string Notes{set;get;} 
} 

現在我有創建一個子類一個方法:

public static ChildViewModel_1 MakeChild_1() 
{ 
    var child= new ChildViewModel_1 
    { 
     Id = ... 
     Name = ... 
     ...And another parent properties... 
     Note = ... 
    } 
    return child; 
} 

他們有很多的simular代碼與父母的階級屬性。
我如何使方法來填充父類字段並使用它來創建子類?

我想:

public static ParentViewModel MakeParent() 
{ 
    var parent = new ParentViewModel 
    { 
     Id = ... 
     Name = ... 
     ...And another properties... 
    } 
    return parent; 
} 

public static ChildViewModel_1 MakeChild_1() 
{ 
    var parent = MakeParent(); 
    var child= parent as ChildViewModel_1; 
    child.Note = ... 

    return child; 
} 

但果然我獲得child = null
我讀this但看起來很困難。
任何建議?

回答

1

在Dia lecticus的答案,這裏是你如何做到這一點:

class Parent 
{ 
    public string Name { get; set; } 
    public int ID { get; set; } 
} 

class Child : Parent 
{ 
    public string Note { get; set; } 
} 

class Factory 
{ 
    public static Parent MakeParent() 
    { 
     var parent = new Parent(); 
     Initialize(parent); 

     return parent; 
    } 

    private static void Initialize(Parent parent) 
    { 
     parent.Name = "Joe"; 
     parent.ID = 42; 
    } 

    public static Child MakeChild() 
    { 
     var child = new Child(); 
     Initialize(child); 

     child.Note = "memento"; 

     return child; 
    } 
} 
2

使孩子,然後從父母調用一些函數設置父特定值。然後調用小孩的功能來製作兒童特定的值。

父特定的初始化可以在父類的構造函數中。

0

使用constructors

在基類和子類指定一個結構,利用像構造函數:

public class ParentViewModel 
{ 
    public int Id { set; get; } 
    public string Name { set; get; } 

    protected ParentViewModel(int Id, string Name) 
    { 
     this.Id = Id; 
     this.Name = Name; 
    } 
} 

public class ChildViewModel_1 : ParentViewModel 
{ 
    public string Notes { set; get; } 

    public ChildViewModel_1(int Id, string Name, string Notes) 
     : base(Id, Name) //Calling base class constructor 
    { 
     this.Notes = Notes; 
    } 

    public static ChildViewModel_1 MakeChild_1() 
    { 
     return new ChildViewModel_1(0, "Some Name", "Some notes"); 
    } 
} 

(不知道爲什麼你需要靜態方法來創建對象,如果你的靜態方法是您的子類的一部分,並且您只想通過此方法公開對象創建,然後使您的子構造函數private