委托的参数传递
public static List<T> GetDataList<T>(String sql, Func<IDataReader, T> build)
{
using (SqlConnection conn = GetSqlConnection())
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
List<T> list = new List<T>();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
T t = build(reader);
if (t==null) continue;
list.Add(t);
}
return list;
}
}
}
protected void Init_PeopleChoice()
{
String sql = "Select Id,username From nodemanager where "+
"isinfo=1 order by id desc";
Id_UserName t = new Id_UserName();
List<ListItem> list = SqlHelper.GetDataList(sql, Func < IDataReader, Id_UserName > builder);
}
protected Id_UserName builder(SqlDataReader reader)
{
Id_UserName t = new Id_UserName();
t.id = reader.GetString(0).Trim().ToString();
t.username = reader.GetString(1).Trim().ToString();
return t;
}
class Id_UserName
{
public String id { get; set; }
public String username { get; set; }
}
public static List<T> GetDataList<T>(string sql) where T : new()
{
return GetDataList(sql, r => new T());
}