c# – 使用List更好,更干净的方法

我正在寻找几个更好的方法来使用List在我正在工作的几个应用程序.我目前的实现看起来像这样.

MyPage.aspx.cs

protected void Page_Load(object sender,EventArgs e)
{
    BLL.PostCollection oPost = new BLL.PostCollection();
    oPost.OpenRecent();
    rptPosts.DataSource = oArt;
    rptPosts.DataBind();
}

BLL课程

public class Post
{
    public int PostId { get; set; }
    public string PostTitle { get; set; }
    public string PostContent { get; set; }
    public string PostCreatedDate { get; set; }

    public void OpenRecentinitFromrow(DaTarow row)
    {
        this.PostId = (int) row["id"];
        this.PostTitle = (string) row["title"];
        this.PostContent = (string) row["content"];
        this.PostCreatedDate = (DateTime) row["createddate"];
    }
}
public class PostCollection : List<Post>
{
    public void OpenRecent()
    {
        DataSet ds = DbProvider.Instance().Post_ListRecent();
        foreach (DaTarow row in ds.Tables[0].Rows)
        {
            Post oPost = new Post();
            oPost.OpenRecentinitFromrow(row);
            Add(oPost);
        }
    }
}

在这个工作一切都很好,我只是想知道是否有任何改进方法,只是让它更清洁,不得不使用两个不同的类做一些我认为可以发生在一个类或使用一个接口

解决方法

一方面,我不会从列表< T> – 你不是真的专攻行为.

我还建议您可以使Post不可变(至少在外部),并编写一个基于DaTarow的静态方法(或构造函数)来创建一个

public static Post FromDaTarow(DaTarow row)

同样,您可以使用列表方法

public static List<Post> RecentPosts()

它们返回它们.诚然,在某种类型的DAL类中,可能会更好地使用实例方法,这将允许嘲笑等.或者,在Post:

public static List<Post> ListFromDataSet(DataSet ds)

现在,对于使用List< T>本身 – 你是否使用.NET 3.5?如果是这样,你可以使用LINQ来使它变得更加清洁

public static List<Post> ListFromDataSet(DataSet ds)
{
    return ds.Tables[0].AsEnumerable()
                       .Select(row => Post.FromDaTarow(row))
                       .ToList();
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...