C#项目优化
1.读取的封装
public static List<T> ConvertData<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; } //调用 List<User> list = new List<User>(); SqlDataReader sdr = cmd.ExecuteReader(); list = ConvertData<User>(sdr);
/// <summary> /// SqlDataReader读取封装对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sdr"></param> /// <returns></returns> public static T ConvertObject<T>(SqlDataReader sdr) { Type type = typeof(T); PropertyInfo[] properties = type.GetProperties(); T model = Activator.CreateInstance<T>(); while (sdr.Read()) { 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]; //将字段的值赋值给T中的属性 properties[i].SetValue(model, value, null); } } } } return model; }