我正在寻找几个更好的方法来使用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();
- }