項目框架中有一個很實用的方法,它用來獲取客戶端post的數據,并自動賦值到對象各屬性,這樣后臺少寫了很多代碼。但是對于有主表、子表的表單,框架中沒有提供自動給子表對象各屬性賦值的方法,每次都要寫很多代碼,各種判斷,各種循環,一個屬性一個屬性地賦值,很不方便,所以我就嘗試寫了一個自動賦值的方法,用到了C#反射的知識,當然,還不夠完善,方法代碼如下:
public List<T> GetList<T>(MvcContext ctx, string label) where T : new(){ List<T> tList = new List<T>(); int count = 0; // 獲取數據條數 PRopertyInfo[] pInfoList = (typeof(T)).GetProperties(); foreach (PropertyInfo pInfo in pInfoList) { string values = ctx.Post(label + "." + pInfo.Name); if (!strUtil.IsNullOrEmpty(values)) { count = values.Split(',').Length; break; } } // 給每條數據賦值 for (int i = 0; i < count; i++) { T t = new T(); PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties(); foreach (PropertyInfo propertyInfo in propertyInfoList) // 遍歷實體的屬性,以給實體的屬性賦值 { string values = ctx.Post(label + "." + propertyInfo.Name); if (!strUtil.IsNullOrEmpty(values)) { string[] valueArray = values.Split(','); if(!strUtil.IsNullOrEmpty(valueArray[i])) { #region 判斷實體的屬性的類型并賦值 if (propertyInfo.PropertyType == typeof(int)) { int val = int.Parse(valueArray[i]); propertyInfo.SetValue(t, val, null); } if (propertyInfo.PropertyType == typeof(decimal)) { decimal val = decimal.Parse(valueArray[i]); propertyInfo.SetValue(t, val, null); } if (propertyInfo.PropertyType == typeof(string)) { string val = valueArray[i]; propertyInfo.SetValue(t, val, null); } if (propertyInfo.PropertyType == typeof(DateTime)) { DateTime val = DateTime.Parse(valueArray[i]); propertyInfo.SetValue(t, val, null); } #endregion } } } tList.Add(t); } return tList;}方法的使用如下:
List<IMP_PurchasePayRealDtl> purchasePayRealDtlList = GetList<IMP_PurchasePayRealDtl>(ctx, "purchasePayRealDtl");
新聞熱點
疑難解答