C#反射字段复制给实体model
调用格式:ForOrm.Do<T>(ds.Tables[0].Rows[0]);
T:为实体名
/// <summary>
/// 反射 字段复制给model
/// </summary>
public static T Do<T>(DataRow row)where T:new() {
//初始化
T t = new T();
//得到类型
Type type = t.GetType();
//属性集合
PropertyInfo [] ps = type.GetProperties();
//赋值、格式转换
foreach (PropertyInfo p in ps) {
var _data = row[p.Name];
if (_data != null && _data != DBNull.Value)//非空
{
if (p.PropertyType == typeof(System.Nullable<System.DateTime>))//空时间
p.SetValue(t, DateTime.Parse(_data.ToString()), null);
else if (p.PropertyType == typeof(System.Nullable<System.Decimal>))//空Decimal
p.SetValue(t, Decimal.Parse(_data.ToString()), null);
else if (p.PropertyType == typeof(System.Nullable<System.Int32>))//空Decimal
p.SetValue(t, Int32.Parse(_data.ToString()), null);
else
p.SetValue(t, Convert.ChangeType(_data, p.PropertyType), null);
}
}
return t;
}
查看更多关于C#反射字段复制给实体model的详细内容...