通过反射填充泛型集合List的方法
public static List<T> FillEntityList<T>(System.Data.IDataReader dr)
{
List<T> result = new List<T>();
while (dr.Read())
{
//由于是是未知的类型,所以必须通过Activator.CreateInstance()方法来依据T的类型动态创建数据实体对象
T entity = Activator.CreateInstance();
//通过反射取得对象所有的pInfo
foreach (System.Reflection.PropertyInfo pInfo in typeof(T).GetProperties())
{
//BindingFieldAttribute为自定义的Attribute,用于与数据库字段进行绑定
foreach (BindingFieldAttribute attr in pInfo.GetCustomAttributes(typeof(BindingFieldAttribute), true))
{
try
{
int nIndex = dr.GetOrdinal(attr.FieldName); //取得当前数据库字段的顺序
if (dr.GetValue(nIndex) != DBNull.Value)
{
//将DataReader读取出来的数据填充到对象实体的属性里
pInfo.SetValue(entity, Convert.ChangeType(dr.GetValue(nIndex), pInfo.PropertyType), null);
}
}
catch { break; }
}
}
result.Add(entity); //将数据实体对象add到泛型集合中
}
return result;
}


浙公网安备 33010602011771号