重发,

jianjialin 2009-04-27 06:40:02

public static IList<T> FillDataListGeneric<T>(System.Data.SqlClient.SqlDataReader reader) where T : class
{
//实例化一个List<>泛型集合
IList<T> DataList = new List<T>();
while (reader.Read())
{
//由于是是未知的类型,所以必须通过Activator.CreateInstance<T>()方法来依据T的类型动态创建数据实体对象
T RowInstance = Activator.CreateInstance<T>();
//通过反射取得对象所有的Property
foreach (PropertyInfo Property in typeof(T).GetProperties())
{
try
{
//取得当前数据库字段的顺序
if (reader[Property.Name] != DBNull.Value)
{
//将DataReader读取出来的数据填充到对象实体的属性里
Property.SetValue(RowInstance, Convert.ChangeType(reader[Property.Name], Property.PropertyType), null);
}
}
catch
{
break;
}

}
//将数据实体对象add到泛型集合中
DataList.Add(RowInstance);
}
return DataList;
}

protected void Button1_Click(object sender, EventArgs e)
{
string sql = "select * from selectquestions";
IList<DXN.Model.SelectQuestions> lst = FillDataListGeneric<DXN.Model.SelectQuestions>(DXN.DBUtility.DbHelperSQL.ExecuteReader(sql));

}

这是一个获得数据集合的方法,按下Button1按钮得到集合的速度比

//这是直接用dbHelperSql访问数据库返回ILIST结果。可以认为是多层里面的 (new Bll.Info()).GetList()方法 T这里假设为DXN.Model.SelectQuestions
string sql = "select * from SelectQuestions ";
IList <DXN.Model.SelectQuestions > lst = DbHelperSQL.ExecuteReader(sql);

直接取数据慢了两倍多点
不过可以省却不少的代码。
请问这样写可以不?需要注意的地方。

本人小菜鸟~,如果非常可笑还请见谅~

...全文
138 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
jianjialin 2009-04-27
  • 打赏
  • 举报
回复
谢谢LZ, 受教了。

工作了一年了,却还是经常写出垃圾代码。

还得多多积累经验。

Sysping1 2009-04-27
  • 打赏
  • 举报
回复
[Quote=引用楼主 jianjialin 的帖子:]
C# code
public static IList<T> FillDataListGeneric<T>(System.Data.SqlClient.SqlDataReader reader) where T : class
{
//实例化一个List<>泛型集合
IList<T> DataList = new List<T>();
while (reader.Read())
{
//由于是是未知的类型,所以必须通过Activator.CreateInstance<T>()方法来依据T的类型动态创建数据实体对象
T RowInstance = Activato…
[/Quote]
一般来讲开发效率与运行性能难以调和。
以上我觉得从细节修整下会好些
1: try 太频,放外面些
2: foreach (PropertyInfo Property in typeof(T).GetProperties())
改成2句:
PropertyInfo[] props = typeof(T).GetProperties();
foreach (PropertyInfo Property in props)
3:这句最影响性能:
[u]Convert.ChangeType(reader[Property.Name], Property.PropertyType)u]
这样做:
  if (!reader[Property.Name].GetType().equal(Property.PropertyType))
{
Property.SetValue(RowInstance, Convert.ChangeType(reader[Property.Name], Property.PropertyType), null);
}else
{
Property.SetValue(RowInstance, reader[Property.Name], null);
}


4: 没办法,ORM其实这样搞的,只是他们会搞Cache对象而已!
兔儿爷 2009-04-27
  • 打赏
  • 举报
回复
访问我的博客 程序员日记 http://www.ideaext.com
jianjialin 2009-04-27
  • 打赏
  • 举报
回复
郁闷啊。 这次忘记写标题了。

顶顶顶

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧