110,571
社区成员
发帖
与我相关
我的任务
分享
public static T CreateItem<T>(DataRow row)
{
T obj = default(T);
//object value;
if (row != null)
{
obj = Activator.CreateInstance<T>();
foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
try
{
object value = row[column.ColumnName];
prop.SetValue(obj, value, null);
//prop.SetValue(obj, Convert.ChangeType(value, prop.PropertyType), null);
//value = null;
//prop = null;
}
catch
{
// You can log something here
throw;
}
}
}
return obj;
}
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
//////////////////////////////////
prop.SetValue(obj, value, null);
此处prop已经获取了obj.GetType()的类型了,你在prop.SetValue中全部转成string是不行的吧?[/quote]
如果不转可以不?
prop.SetValue(obj, row[column.ColumnName], null);[/quote]
不转不又是以前那个错误?
类型“System.DBNull”的对象无法转换为类型“System.String”
不过我现在解决问题了。
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
try
{
object value = row[column.ColumnName];
if (column.DataType == typeof(System.String))
{
value = row[column.ColumnName].ToString();
}
prop.SetValue(obj, value, null);
}
catch
{
// You can log something here
throw ;
}
加入这个判断后就解决问题了。
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
//////////////////////////////////
prop.SetValue(obj, value, null);
此处prop已经获取了obj.GetType()的类型了,你在prop.SetValue中全部转成string是不行的吧?[/quote]
如果不转可以不?
prop.SetValue(obj, row[column.ColumnName], null);
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
//////////////////////////////////
prop.SetValue(obj, value, null);
此处prop已经获取了obj.GetType()的类型了,你在prop.SetValue中全部转成string是不行的吧?PropertyInfo props = obj.GetType().GetProperties().ToDictionary(p => p.Name, p => p, StringComparer.OrdinalIgnoreCase);
PropertyInfo prop;
foreach (DataColumn column in row.Table.Columns)
{
if(props.TryGetValue(column.ColumnName, out prop))
{
try
{
object value = row[column.ColumnName];
prop.SetValue(obj, value, null);
//prop.SetValue(obj, Convert.ChangeType(value, prop.PropertyType), null);
//value = null;
//prop = null;
}
catch
{
// You can log something here
throw;
}
}
}