我正在嘗試使用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;
}
什麼是你的問題?你對我們有什麼期望?爲你寫嗎?你在正確的軌道上。繼續... – I4V
編輯。對不起,我非常專注於解釋我實際上並沒有問的問題lol – gwin003