2012-10-17 49 views
1

我有一個對象,看起來像這樣:避免物體內返回一個對象

public class MyObject 
{ 
    public int UserID {get;set;} 
    public List<SomeObjects> {get;set;} 
    public List<SomeOtherObjects {get;set} 
    public MyObject TheObjectForDB {get;set} //HERE: creating a new object 

    public MyObject(int TheUserID) 
    { 
     this.UserID = TheUserID; 
    } 

    public LoadTheObjectFromDatabase() 
    { 
     MyQueries TheQueries = new MyQueries(); 
     TheObjectForDB = TheQueries.LoadFromDB(UserID) //HERE: object for DB work 

     this.List<SomeObjects> = TheObjectForDB.List<SomeObjects>; 
     this.List<SomeOtherObjects> = TheObjectForDB.List<SomeOtherObjects>; 
    } 
} 

數據庫查詢基本返回相同的對象類型:

LoadFromDB = from... 
      select new MyObject(TheUserID){...} 

如何刪除這種冗餘我需要實例化另一個相同類型的對象來填充初始對象?

感謝您的建議。

回答

3

使LoadTheObjectFromDatabase() a static方法返回一個新的MyObject

public class MyObject 
{ 
    public int UserID {get;set;} 
    public List<SomeObjects> {get;set;} 
    public List<SomeOtherObjects {get;set} 

    public MyObject(int TheUserID) 
    { 
     this.UserID = TheUserID; 
    } 

    public static MyObject LoadTheObjectFromDatabase(int userid) 
    { 
     MyQueries TheQueries = new MyQueries(); 
     MyObject TheObjectForDB = TheQueries.LoadFromDB(userid) //HERE: object for DB work 

     return TheObjectForDB; 
    } 
} 

然後,而不是做MyObject newObj = new MyObject(); newObj.LoadTheObjectFromDatabase();,你只是做MyObject newObj = MyObject.LoadTheObjectFromDatabase();

+0

周圍的靜態方法,這我試圖避免任何方式。 – frenchie

+0

@frenchie - 靜態方法有什麼問題? –

+0

@frenchie - 當然有選擇,儘管這是最好的方法。你爲什麼要避免它? – Bobson