/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> /// <exception cref="FormatException"></exception> public static T GetEntity <T>() where T : new() { const bool allowError = false; global::System.Collections.Specialized.NameValueCollection form = global::System.Web.HttpContext.Current.Request.Form; Type type = typeof(T); object t = Activator.CreateInstance(type); PropertyInfo[] pros = type.GetProperties(); FormFieldAttribute[] fieldAttrs; FormFieldAttribute attr; string value; int tmpInt; Type strType = typeof(String); //字符串类型 Type bitType = typeof(Boolean); //布尔值类型 Type proType = null; //属性类型 foreach (PropertyInfo pro in pros) { if (!pro.CanWrite) { continue; } fieldAttrs = pro.GetCustomAttributes(typeof(FormFieldAttribute), false) as FormFieldAttribute[]; if (fieldAttrs != null && fieldAttrs.Length != 0) { attr = fieldAttrs[0]; value = form[pro.Name] ?? (form["field_" + pro.Name] ?? ""); proType = pro.PropertyType; object obj; try { obj = CollectionExtensions.GetPropertyValue <T>(pro, strType, bitType, proType, value); if (obj != null) { pro.SetValue(t, obj, null); } } catch (FormatException exc) { if (allowError) { throw new FormatException("转换错误,属性名:" + pro.Name); } } //if (pro.PropertyType.IsEnum) //{ // int.TryParse(value, out tmpInt); // pro.SetValue(t, tmpInt, null); //} //else //{ // try // { // pro.SetValue(t, Convert.ChangeType(value, pro.PropertyType), null); // } // catch (FormatException exc) // { // throw new FormatException("转换错误,属性名:" + pro.Name); // } //} } } return((T)t); }