我覺得很奇怪,你想從當前實例中返回一個類的當前實例的引用。你會不會有這樣的參考,爲了訪問對象的屬性和方法?你可能在想克隆嗎?
除非我錯過了一些關於你的模型的東西,看起來好像建立了一個初始化方案,一些無聊的Property定義,或許還有一個工廠類可能更像你正在尋找的東西。您似乎也可能考慮將您的父母設爲ID作爲不可變屬性,儘管您的要求可能會爲此創建一個真實的原因。
這裏有一些可能有用的類def。現在在聖路易斯早些時候,我還沒有適當地氣候,所以我可能會錯過一些東西。 。 。 ;-)
家長:
public class Parent
{
protected string _id;
// Protected default constructor so tht this class can be inherited:
protected Parent() { }
// REquired to set ID at initialization;
public Parent(String ID)
{
_id = ID;
}
// Read-only:
public String ID
{
get { return _id; }
}
// This seems a little dodgy. Why would you want to return a reference
// to the current instance as a result of resetting the ID?
public Parent SetID(String ID)
{
_id = ID;
return this;
}
}
家長廠:
public class ParentFactory
{
public static Parent NewParent(String ID)
{
Parent newParent = new Parent(ID);
return newParent;
}
}
的孩子:
public class Child : Parent
{
private string _name;
// Protected default constructor so tht this class can be inherited:
protected Child() { }
// Initialize a new Child with the ID property required for the parent:
public Child(String ID)
{
base.SetID(ID);
}
// Initialize a new child with both properties set:
public Child(String ID, String Name) : this(ID)
{
_name = Name;
}
// This could be read-only as well:
public String Name
{
get { return _name; }
set { _name = value; }
}
// Again, seems kinda dodgy:
public Child SetName(String name)
{
return this;
}
}
一個孩子廠:
public class ChildFactory
{
public static Child NewChild(String ID)
{
Child newChild = new Child(ID);
return newChild;
}
public static Child NewChild(String ID, String Name)
{
Child newChild = new Child(ID, Name);
return newChild;
}
}
@ L.B - 家長可以有許多孩子...... – SexyMF
@ L.B這是錯誤的,因爲您不知道在您寫入父類時您將擁有多少個孩子類, –
如果你沒有引用Child類,你的(Child)將不會編譯。如果孩子不在編譯時間... –