赞
踩
public class BaseEntity where T : BaseEntity
{
public BaseEntity()
{
}
public BaseEntity(DataTable table, int indexRow)
{
InitObjInfo(table, indexRow);
}
///
/// 初始化实体类对象信息
///
///
///
private void InitObjInfo(DataTable table, int indexRow)
{
for (int i = 0; i < table.Columns.Count; i++)
{
// 按列的名称,从当前对象中获取同名属性
PropertyInfo pInfo = this.GetType().GetProperty(table.Columns[i].ColumnName);
// 存在该属性
if (pInfo != null)
{
object value = table.Rows[indexRow][table.Columns[i].ColumnName];
value = value == DBNull.Value ? string.Empty : value;
// 如果对象属性定义的类型和table的列的类型一致
if (pInfo.PropertyType == table.Columns[i].DataType)
{
pInfo.SetValue(this, value, null);
}
else
{
// 如果对象类型是枚举类型
if (pInfo.PropertyType.IsEnum)
{
// 数据库中保存的是int类型,则直接为枚举赋值
if (value.GetType() == typeof(int))
{
pInfo.SetValue(this, value, null);
}
// 如果数据库中保存的是string类型
if (value.GetType() == typeof(string))
{
pInfo.SetValue(this, Enum.Parse(pInfo.PropertyType, value.ToString(), false), null);//赋值
}
}
}
}
}
}
///
/// 返回一个类型为T的对象
///
/// 数据表
/// 表中的第几行
/// object
protected static T CreateInstance(DataTable table, int rowIndex)
{
if (table == null)
{
return null;
}
if (table.Rows.Count > rowIndex)
{
// 使用反射创建对象
return (T)System.Activator.CreateInstance(typeof(T), table, rowIndex);
}
else
{
return null;
}
}
///
/// 返回一个泛型列表
///
/// 数据表
///
protected static List CreateInstances(DataTable table)
{
List instances = new List();
for (int i = 0; i < table.Rows.Count; i++)
{
T instance = CreateInstance(table, i);
if (instance != null)
{
instances.Add(instance);
}
}
return instances;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。