標籤:style blog http color io for ar 資料 div
//新版本,可以再globa.ascx裡面設定開發模式//以便於調試錯誤//表單轉實體物件V2版public class HttpRequestHelper { /// <summary> /// 開發模式,設定成開發模式後拋出異常,可查看出錯的屬性,和類型 /// </summary> public static bool DevMode { get; set; } #region 表單轉換成實體模型 /// <summary> /// 表單轉換成實體模型 /// 用法:1、插入,先new一個對象傳入; /// 2、更新,先從資料庫查出這個對象傳入 /// </summary> /// <param name="obj">泛型對象</param> /// <returns></returns> public static T ConvertForm2Model<T>(T obj) { if (null == obj) { obj = default(T); obj = Activator.CreateInstance<T>(); } Type type = typeof(T); foreach (var p in type.GetProperties()) { string result = HttpContext.Current.Request.Params[p.Name]; if (!string.IsNullOrWhiteSpace(result)) { try { p.SetValue(obj, Convert.ChangeType(result, p.PropertyType), null); } catch(Exception ex) { if (DevMode) { throw new Exception("類型轉換錯誤,變數:" + p.Name + ",類型:" + p.PropertyType + ",錯誤資訊:" + ex.Message); } else { //記錄日誌。。。。 } } } } return obj; } #endregion }
/////////////////////各位有什麼好想法,請給個建議//[email protected]//////////////////public class HttpRequestHelper<T> where T : class,new() { #region 表單轉換成實體模型 /// <summary> /// 表單轉換成實體模型 /// 用法:1、插入,先new一個對象傳入; /// 2、更新,先從資料庫查出這個對象傳入 /// </summary> /// <param name="obj">泛型對象</param> /// <returns></returns> public static T ConvertForm2Model(T obj=null) { if (null == obj) { obj = default(T); obj = Activator.CreateInstance<T>(); } Type type = typeof(T); foreach (var p in type.GetProperties()) { string result = HttpContext.Current.Request.Params[p.Name]; if (!string.IsNullOrWhiteSpace(result)) { try { p.SetValue(obj, Convert.ChangeType(result, p.PropertyType), null); } catch(Exception ex) { throw new Exception("類型轉換錯誤,變數:" + p.Name + ",類型:" + p.PropertyType+",錯誤資訊:" + ex.Message); } } } return obj; } #endregion }
經常遇到 int Age=Convert.ToInt32(this.txtAge.Text);
這種蛋疼的代碼,特寫次方法。
之所以拋出異常是希望知道轉換失敗,格式錯誤的屬性是什麼,方便調試。
ASP.NET From表單轉實體類