62,266
社区成员
发帖
与我相关
我的任务
分享
///<summary>
///SqlDataReader转换成List<t>
///</summary>
///<param name="reader">数据</param>
///<returns></returns>
internal List<T> SqlPar_List<T>(DbDataReader reader) where T : new()
{
List<T> list;
//Type type = typeof(T);
string tempName = string.Empty;
if (reader.HasRows)
{
list = new List<T>();
while (reader.Read())
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
if (SqlPar_readerExists(reader, tempName))
{
if (!pi.CanWrite)
{
continue;
}
var value = reader[tempName];
if (value != DBNull.Value)
{
pi.SetValue(t, value, null);
}
}
}
list.Add(t);
}
reader.Close();
return list;
}
return null;
}
List<ABC> lst = ...............
foreach(var x in lst)
{
dynamic y = x;
var z = y.value;
}这样,或者随时可以写List<ABC> lst = ...............
var lst1 = lst.Cast<dynamic>();
foreach (var y in lst1)
{
var z = y.value;
}
这样。代码 lst.Cast<dynamic>() 既可以随便得到 List<dynamic>,跟 DbDataReader 根本没有关系。
关键是,写代码必须尽可能地具体,而不是尽可能地空洞。真正懂得抽象的人,反而代码非常具体,最好的抽象的艺术性就在于月抽象则越简洁而具体,不把精力放在不必要的走弯路的抽象方式上。
internal List<T> SqlPar_List<T>(DbDataReader reader) where T : new()
{
List<T> list=new List<T>();
Type type = typeof(T);
if (reader.HasRows)
{
while (reader.Read())
{
object note = Activator.CreateInstance(type);
foreach (var item in type.GetProperties())
{
item.SetValue(note, reader[item.Name]);
}
list.Add(note as T);
}
reader.Close();
return list;
}
return list;
}