再灌一篇,把DataReader取的数据反射成List<entity>
Code
public class ListEx<T> : List<T>
{
/// <summary>
/// 从DataReader中加载数据
/// </summary>
/// <param name="reader"></param>
public void Load(IDataReader reader)
{
this.Clear();
while (reader.Read())
{
//获取字段总数
int colCount = reader.FieldCount;
//获取实体类型
Type objType = typeof(T);
//实例化实体
ConstructorInfo constructor = objType.GetConstructor(Type.EmptyTypes);
T entity = (T)constructor.Invoke(null);
//给实体赋值
for (int i = 0; i < colCount; i++)
{
PropertyInfo property = objType.GetProperty(reader.GetName(i));
if (property != null)
{
property.SetValue(entity, reader[i], null);
}
}
//将实体添加至集合中
this.Add(entity);
}
reader.Dispose();
}
}