2013-02-21 74 views
-2

我想知道是否有人可以幫助我填充派生類的基本屬性的最佳方式。我想使用一種方法來填充基地的屬性,無論是使用基地還是兒童。填充基礎屬性的最佳方式是什麼?

這裏是什麼,我問一個例子:

public class Parent 
{ 
    public string Id {get; set;} 
} 

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

public Parent GetParent(int ID) 
{ 
    Parent myParent = new Parent(); 
//Lookup and populate 
return Parent; 
} 

public Child GetChild(string name) 
{ 
Child myChild = new Child(); 

//Use the GetParent method to populate base items 
//and then 
//Lookup and populate Child properties 

return myChild; 
} 
+2

通過構造函數填充? – sll 2013-02-21 15:54:20

+0

可能重複[填充基類與子類?](http://stackoverflow.com/questions/3649354/populate-base-class-along-with-child-class) – MethodMan 2013-02-21 15:55:22

+0

你可以做什麼'sll'有建議或者你可以採取繼承路線.. – MethodMan 2013-02-21 15:55:59

回答

2

的構建函數我想你可能會過於複雜的事情一點。看看這段代碼中使用繼承和構造函數初始化對象:

public class Parent 
{ 
    public string Id {get; set;} 

    public Parent(string id) 
    { 
     Id = id; 
    } 
} 

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

    public Child(string id, string name) : base(id) // <-- call base constructor 
    { 
     Name = name; 
    } 
} 

它使用構造函數初始化和base keyword來調用派生類的父類的構造。除非你真的需要一個工廠方法來構建你的對象,否則我會去這個方向。

1

事情是這樣的,如果你不想做的constructor

注意:constructor並不總是被調用,特別是如果類型使用某些序列化器desirialized。

public class Parent 
{ 

    public string Id {get; set;} 

    public virtual void InitPorperties() { 
     //init properties of base 
    } 

} 


public class Child : Base { 

    public override void InitProperties() { 
     //init Child properties 
     base.InitProperties(); 
    } 
} 

這之後您可以使用它像:

public Parent GetParent(int ID) 
{ 
    var myParent = new Parent(); 
    parent.InitProperties(); 
    return myParent; 
} 

public Parent GetChild(int ID) 
{ 
    var child= new Child(); 
    child.InitProperties(); 
    return child; 
} 

正如任何有硬幣的另一面:調用者必須調用在奧德InitProperties方法來得到正確初始化對象。

如果串行/ desialization是不是在你的情況的擔憂,堅持構造,在實踐中調用這個方法裏面每一種類型(ParentChild

1

如果你不想使用標準的辦法只有

Child myChild = new Child(); 
    myChild.Name = "name"; 
    myChild.Id = "1"; 

您可以通過這樣的構造填充它們。

public class Parent 
    { 
     public Parent(string id) 
     { 
      Id = id; 
     } 

     public string Id { get; set; } 
    } 

    public class Child : Parent 
    { 
     public Child(string id, string name) 
      : base(id) 
     { 
      name = Name; 
     } 

     public string Name { get; set; } 
    } 

當你isntanciate它

 Child myChild = new Child("1", "name"); 

這在我看來是一個相當巧妙的方法來做到這一點。