2010-11-01 74 views
0

我想定義一個派生自System.Data.DataTable的類。
這個類有一個PopulateColumns方法,你可以猜測填充DataTable。 我希望此方法能夠動態填充任何數字自定義數據類型的數據表列。 (請參見下面的澄清我的代碼) 我試着用Dictionary<strin,Type>,而不是傳遞所有參數逐個:使用自定義類型填充數據表列

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

,並稱之爲:

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); 

這工作得很好。但它不能接受兩個相同的列(因爲列名是字典中的鍵)。
我知道我不需要傳遞兩個同名的列。但我只是好奇,如果有更好的方法來做到這一點。

回答

2

它更簡單的比你想:

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

或者,你可以建立事前名單:(數組,集合等方面有AddRange()成員)

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

    testDt.Columns.AddRange(columns); 

+0

謝謝。好像我需要睡覺......不知道我怎麼看不到這些! – Kamyar 2010-11-01 21:11:03

相關問題