BindingList vs DataTable vs List集合

时间:2019-06-16 09:54:20

标签: c# datagridview

我试图了解这三个集合之间的差异。 我的概念是使用数据源填充datagridview。在我将要描述的所有方法中,我得到的结果相同,没有任何区别。

private void button1_Click(object sender, EventArgs e)
    {
        dataGridView1.DataSource = dt();
        dataGridView2.DataSource = dt2();
        dataGridView3.DataSource = dt3();
    }

    public class Foo
    {
        public Foo(string name,int age)
        {
            Name = name;
            Age = age;
        }
        [DisplayName("CustomerName")]
        public string Name { get; set; }
        [DisplayName("CustomerAge")]
        public int Age { get; set; }
    }

    //Method 1
    private BindingList<Foo> dt()
    {
        BindingList<Foo> tmp = new BindingList<Foo>();
        tmp.Add(new Foo (  "Dimitris", 28 ));
        tmp.Add(new Foo (  "Dio",  32 ));
        return tmp;
    }

    //Method 2
    private DataTable dt2()
    {
        DataTable tmp = new DataTable();
        tmp.Columns.Add("Name", typeof(string)).Caption = "CustomerName";
        tmp.Columns.Add("Age", typeof(int)).Caption = "CustomerAge";
        DataRow dr = null;

        dr = tmp.NewRow();
        dr["Name"] = "Dimitris";
        dr["Age"] = 28;
        tmp.Rows.Add(dr);

        dr = tmp.NewRow();
        dr["Name"] = "Dio";
        dr["Age"] = 32;
        tmp.Rows.Add(dr);

        return tmp;
    }

    //Method 3
    private List<Foo> dt3()
    {
        List<Foo> tmp = new List<Foo>();
        tmp.Add(new Foo("Dimitris", 28));
        tmp.Add(new Foo("Dio", 32));
        return tmp;
    }

还有什么更好的方法吗?它们在性能上有什么不同吗?哪些是最佳做法?

0 个答案:

没有答案