使用自定义类型填充数据表列

Kam*_*yar 2 c# datatable populate .net-3.5

我想定义一个派生自 System.Data.DataTable 的类。你可以猜到,
这个类有一个方法来填充数据表。PopulateColumns我希望此方法能够使用任意数量的自定义数据类型动态填充数据表列。(请参阅下面的代码以进行澄清)我尝试使用Dictionary<strin,Type>,而不是一一传递所有参数:

public void Populate(Dictionary<string, Type> dic)
   {
       foreach (var item in dic)
           this.Columns.Add(item.Key, item.Value);
   }  
Run Code Online (Sandbox Code Playgroud)

并称其为:

var testDt = new TestDataTable();
Dictionary<string, Type> dicCols = new Dictionary<string, Type>();
dicCols.Add("Index", System.Type.GetType("System.Int32"));
dicCols.Add("Title", System.Type.GetType("System.String"));
testDt.Populate(dicCols);  
Run Code Online (Sandbox Code Playgroud)

这很好用。但它不能接受具有相同内容的两列(因为列名称是字典中的键)。
我知道我不需要传递两个同名的列。但我只是好奇是否有更好的方法。

Sni*_*ave 7

它比你想象的更简单:

    testDt.Columns.AddRange(new[] 
    {
        new DataColumn("Index", typeof(int)),
        new DataColumn("Title", typeof(string)),
    });
Run Code Online (Sandbox Code Playgroud)

或者,您可以预先构建列表:

    var columns = new[] 
    {
        new DataColumn("Index", typeof(int)),
        new DataColumn("Title", typeof(string)),
    };

    testDt.Columns.AddRange(columns);
Run Code Online (Sandbox Code Playgroud)

(数组、集合等都有一个AddRange()成员。)