2013-04-18 23 views
1

我正在嘗試使用DataTable創建並填充一組對象。我希望創建一個函數,該函數可以根據傳入該函數的type知道要創建的對象類型。然後使用由Activator.CreateInstance(type)或Reflection返回的對象,使用數據集中的數據填充對象字段。這裏是我的功能:動態創建數據集中的不同對象

private object DataTableToObject(DataTable table, Type type) 
{ 
    var obj = Activator.CreateInstance(type); 
    //we are only concerned with the first row here 

    var row = table.Rows[0]; 

    /* do something here to populate the fields of MyObject */ 
} 

我希望能調用這個函數是這樣的...

var dataTable1 = DataTableToObject(dataSet.Tables[dataSet.Tables.IndexOf("MyCustomObject")]); 
MyCustomObject custObj = DataTableToObject(dataTable1, typeof(MyCustomObject)); 

編輯:什麼是填充在運行時的對象領域的最佳方法是什麼?我是否需要使用反射來獲取字段名稱,然後使用字段名稱,以某種方式填充對象?

解決方案!

private T DataTableToObject<T>(DataTable table) 
{ 
    var obj = Activator.CreateInstance(typeof(T)); 

    //we are only concerned with the first row because in our datasets, we should only have one row per table 
    var row = table.Rows[0]; 

    foreach(DataColumn col in table.Columns) 
    { 
     var propInfo = obj.GetType().GetProperty(col.ColumnName); 
     if (propInfo == null) continue; 

     object colValue; 
     if(propInfo.PropertyType == typeof(Guid)) 
      colValue = Guid.Parse(row[col.ColumnName].ToString()); 
     else 
      colValue = Convert.ChangeType(row[col.ColumnName], propInfo.PropertyType); 

     propInfo.SetValue(obj, colValue, null); 
    } 
    return (T) obj; 
} 
+1

什麼是你的問題?你對我們有什麼期望?爲你寫嗎?你在正確的軌道上。繼續... – I4V

+0

編輯。對不起,我非常專注於解釋我實際上並沒有問的問題lol – gwin003

回答

1

首先製作方法通用:

private T DataTableToObject<T>(DataTable table) 

,然後改變它了一點:

var obj = Activator.CreateInstance(typeof(T)); 

,並在方法結束時記得要投它:

return (T)obj; 

現在,當你打電話給它時,它看起來就像這樣:

MyCustomObject custObj = DataTableToObject<MyCustomObject>(dataTable1); 

現在如何填充字段,我會做這樣的事情:

foreach (var col in table.Columns) 
{ 
    var propInfo = obj.GetType().GetProperty(col.Name); 
    if (propInfo == null) { continue; } 

    propInfo.SetValue(obj, row[col.Name], null); 
} 
+0

'var obj = Activator.CreateInstance(typeof(T));'似乎比替代方法更好。我如何訪問'obj'的字段? – gwin003

+0

@ gwin003,查看我編輯的過程以獲取屬性。 –

+0

感謝您的幫助,我現在就試一試。必須稍微調整一下'foreach'循環。如果這有效,我會編輯。 – gwin003