ModelHelper类
public class ModelHelper <T> where T : new()
{
public static T ConvertModel(DataRow dr)
{
T t = new T();
Type modelType = t.GetType();
foreach (PropertyInfo p in modelType.GetProperties())
{
p.SetValue(t, GetDefaultValue(dr[p.Name], p.PropertyType), null);
}
return t;
}
private static object GetDefaultValue(object obj, Type type)
{
if (obj == DBNull.Value)
{
obj = default(object);
}
else
{
obj = Convert.ChangeType(obj, type);
}
return obj;
}
}
范例:
Model model = ModelHelper<Model>.ConvertModel(DataRow)ModelHelper类