从数据集动态创建不同的对象
本文关键字:对象 创建 数据集 动态 | 更新日期: 2023-09-27 18:09:59
我试图使用一个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;
}
首先将方法设为泛型:
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);
}