我有一個類,像這樣:使用工廠方法來構建基礎對象繼承
public class User {
public User() {
// this constructor creates an object representing a brand new user
}
public static User Get(MyDbObject dbObject) {
// this factory method creates an object representing an existing user, from a database object
}
}
和繼承的類,像這樣:
public class ExtendedUser : User {
public object ExtendedProperty { get; set; }
public static ExtendedUser Get(MyDbObject dbObj) {
User usr = User.Get(dbObj);
this = usr; // this does NOT work
this.ExtendedProperty = "just an example";
}
}
本來這是所有工作使用從MyDbObject記錄創建一個對象的重載構造函數,因此ExtendedUser具有這樣的構造函數:
public ExtendedUser(MyDbObject dbObj) : base(dbObj) {
this.ExtendedProperty = "another example, this is how it WAS working";
}
我想擺脫使用構造函數來創建這些對象,而傾向於工廠方法,但是我不會在不調用構造函數的情況下分配基本實例/對象。這可能嗎?
不,不可能。 – MarcinJuraszek
爲什麼你想使用工廠方法而不是構造函數? – khellang