最近在做一个网站,对于开发过程中的一些技巧和问题做一个总结。
本人习惯使用对象操作,感觉对记录操作有点麻烦,所以在数据模型层声明一个对象模型,以便更直观来操作记录。在网上也查找一下这方面的信息。这里分享一下。
/// <summary>
/// 返回泛型集合
/// </summary>
/// <param name=""></param>
/// <returns></returns>
private static List<T> GetList<T>(SqlDataReader sdr)
{
//声明泛型列表
List<T> list = new List<T>();
//获取泛型类型
Type type = typeof(T);
//获取泛型对象的属性
PropertyInfo[] properties = type.GetProperties();
while (sdr.Read())
{
T model = Activator.CreateInstance<T>();
for (int i = 0; i < properties.Length; i++)
{
for (int j = 0; j < sdr.FieldCount; j++)
{
//判断属性的名称和字段的名称是否相同
if (properties[i].Name == sdr.GetName(j))
{
Object value = sdr[j];
//将字段的值赋值给User中的属性
properties[i].SetValue(model, value, null);
}
}
}
list.Add(model);
}
return list;
}
再写一个通用的查询函数,方便使用
/// <summary>
/// 数据库查询
/// </summary>
/// <param name="name">查询字符串</param>
/// <returns>返回泛型List集合</returns>
public static List<T> Select<T>(string cmdstring)
{
SqlConnection scon = GetConnection();
try
{
scon.Open();
SqlCommand cmd = new SqlCommand(cmdstring, scon);
SqlDataReader sdr = cmd.ExecuteReader();
return GetList<T>(sdr);
}
catch
{
return null;
}
finally
{
if (scon.State == ConnectionState.Open)
{
scon.Close();
}
}
}
/// <summary>
/// 返回连接数据库对象
/// </summary>
/// <returns></returns>
private static SqlConnection GetConnection()
{
string sqlcon = ConfigurationManager.AppSettings["ConnectionString"];
return new SqlConnection(sqlcon);
}
本文分享了在网站开发中,通过定义泛型集合返回的技巧,简化了对象模型的操作过程。作者介绍了如何使用反射和泛型来从数据库读取数据并将其转换为特定类型的对象集合,同时提供了一个通用的查询函数,方便后续的数据调用。
1774

被折叠的 条评论
为什么被折叠?



