加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:38:40 所属栏目:百科 来源:网络整理
导读:我正在寻找几个更好的方法来使用List在我正在工作的几个应用程序.我目前的实现看起来像这样. MyPage.aspx.cs protected void Page_Load(object sender,EventArgs e){ BLL.PostCollection oPost = new BLL.PostCollection(); oPost.OpenRecent(); rptPosts.Da
我正在寻找几个更好的方法来使用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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读