c#object / design fundamentals

时间:2012-02-29 21:31:12

标签: c# object

这是一种标准的,良好的做法吗?基本上返回一个自己的列表?实际字段(id,title等)应该是一个单独的类吗? (我见过人们称之为DTO对象)

我正在开始一个项目&我想试试&得到一些基本面 -

谢谢!

public class Calendar
{
    public int id { get; set; }
    public string title { get; set; }

    public List<calendar> GetAll()
    {
        var list = new List<calendar>();

        var db = new mssql2();
        db.set("s1");
        string sql = @"select * from [cal]";
        var dr = db.dr(sql);
        while (dr.Read())
        {
           var e = new calendar();
           e.id = (int)dr["id"];
           e.title = dr["title"].ToString();
           list.Add(e);
        }
        return list;
    }
}

3 个答案:

答案 0 :(得分:7)

您似乎将域模型与数据访问层混合在一起。

将日历保持为自己的类,并且可以创建另一个名为CalendarServiceCalendarRepository的类,它会返回一个Calendar对象列表。

以下是一个例子:

public class Calendar
{
    public Calendar() { }
    public Calendar(int id, string title)
    {
       Id = id;
       Title = title;
    }
    public int Id { get; set; }
    public string Title { get; set; }
}

public class CalendarService
{
    public static List<Calendar> GetAll()
    {
        var list = new List<Calendar>();

        var db = new mssql2();
        db.set("s1");
        string sql = @"select * from [cal]";
        var dr = db.dr(sql);
        while (dr.Read())
        {
            // Use the constructor to create a new Calendar item
            list.Add(new Calendar((int)dr["id"], dr["title"].ToString()));
        }
        return list;
    }
}

答案 1 :(得分:2)

一般的想法是,类表示域对象,类成员表示这些域对象的各种属性。类函数代表对象可以做什么

在您的情况下,将get_all()删除到某个类抽象数据库操作可能更合适。 Calendar将具有日历的功能(获取/设置一些日期,跳过几年,获得/设置一些约会);取决于你想用日历完成什么。

Object design

答案 2 :(得分:0)

您正在紧密耦合数据访问,而您的“get_all”方法甚至不使用日历类型对象中的任何内容。如果,在这种情况下,您的方法不使用它所属的类的实例中的任何数据,那么该方法应该不存在,或者应该是静态方法。我倾向于前者 - 有一个类,其目的是从数据库中检索日历或日历。它是一种更合理的代码组织,更易于测试,可以更容易地从数据层中抽象出来,并且它还使您的数据对象更具可移植性。