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

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

感谢您的建议。

4

1 回答 1

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

于 2012-10-17T17:06:17.447 回答