public T Get<T>(int id) { Type type = typeof(T); string columnStrings = string.Join(",", type.GetProperties().Select(p=>string.Format("[{0}]"))); string sql = string.Format("select {0} from [{1}] where id={2}", columnStrings,type.Name,id); return default(T); }
完整例子
public T Get<T>(int id) { Type type = typeof(T); string columnStrings = string.Join(",", type.GetProperties().Select(p=>string.Format("[{0}]"))); string sql = string.Format("select {0} from [{1}] where id={2}", columnStrings,type.Name,id); object t = Activator.CreateInstance(type); using (SqlConnection conn = new SqlConnection("链接字符串")) { SqlCommand com = new SqlCommand(sql,conn); conn.Open(); SqlDataReader reader = com.ExecuteReader(); if (reader.Read()) { foreach (var item in type.GetProperties()) { item.SetValue(t,reader[item.Name]); } } } return (T)t; }
本文介绍了一种使用C#泛型方法从数据库中根据ID加载特定类型对象的技术。通过反射获取类型的属性,并构建SQL查询语句来选择相应字段。然后使用`Activator.CreateInstance`创建对象,并将查询结果的值设置到对象的属性中。
5114

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



