避免从对象内返回对象

时间:2012-10-17 17:02:22

标签: c#

我有一个看起来像这样的对象:

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){...}

如何在需要实例化另一个相同类型的对象来填充初始对象的情况下,如何删除此冗余?

感谢您的建议。

1 个答案:

答案 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();