111,120
社区成员
发帖
与我相关
我的任务
分享
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是不行的吧?
[/quote]
<T>的属性也是?[/quote]
还真是要确认大小写一直才行。多谢你!
但我目前有别的问题了:
object value = row[column.ColumnName];
这一句中,ColumnName列本身是string类型的,但是允许空,所以数据库里面是null显示的;通过这一句取出来的恐怕是空值,
报错显示是“类型“System.DBNull”的对象无法转换为类型“System.String””
奇怪的是:
此时value的值是 {} 这样的(在VS中断点查看的),我想加个判断语句判断其为空然后赋值string的空值“” ,但是却无法判断,
if (value == "{}") 或者 if (value == null ) 或者 if (value == "") 均不能进入下一步赋值语句,该如何办?
[/quote]
<T>的属性也是?[/quote]
这……我去看看先
[/quote]
<T>的属性也是?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;
}
}
} 