我有一个看起来像这样的对象:
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){...}
如何在需要实例化另一个相同类型的对象来填充初始对象的情况下,如何删除此冗余?
感谢您的建议。
答案 0 :(得分:3)
使LoadTheObjectFromDatabase()
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();