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

前端之家收集整理的这篇文章主要介绍了c# – 使用List更好,更干净的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找几个更好的方法来使用List在我正在工作的几个应用程序.我目前的实现看起来像这样.

MyPage.aspx.cs

  1. protected void Page_Load(object sender,EventArgs e)
  2. {
  3. BLL.PostCollection oPost = new BLL.PostCollection();
  4. oPost.OpenRecent();
  5. rptPosts.DataSource = oArt;
  6. rptPosts.DataBind();
  7. }

BLL课程

  1. public class Post
  2. {
  3. public int PostId { get; set; }
  4. public string PostTitle { get; set; }
  5. public string PostContent { get; set; }
  6. public string PostCreatedDate { get; set; }
  7.  
  8. public void OpenRecentInitFromRow(DataRow row)
  9. {
  10. this.PostId = (int) row["id"];
  11. this.PostTitle = (string) row["title"];
  12. this.PostContent = (string) row["content"];
  13. this.PostCreatedDate = (DateTime) row["createddate"];
  14. }
  15. }
  16. public class PostCollection : List<Post>
  17. {
  18. public void OpenRecent()
  19. {
  20. DataSet ds = DbProvider.Instance().Post_ListRecent();
  21. foreach (DataRow row in ds.Tables[0].Rows)
  22. {
  23. Post oPost = new Post();
  24. oPost.OpenRecentInitFromRow(row);
  25. Add(oPost);
  26. }
  27. }
  28. }

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

解决方法

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

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

  1. public static Post FromDataRow(DataRow row)

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

  1. public static List<Post> RecentPosts()

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

  1. public static List<Post> ListFromDataSet(DataSet ds)

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

  1. public static List<Post> ListFromDataSet(DataSet ds)
  2. {
  3. return ds.Tables[0].AsEnumerable()
  4. .Select(row => Post.FromDataRow(row))
  5. .ToList();
  6. }

猜你在找的C#相关文章