public static T NameValue2Model <T>(global::System.Collections.Specialized.NameValueCollection data) where T : new() { T model = new T(); foreach (PropertyInfo field in typeof(T).GetProperties()) { foreach (string key in data.AllKeys) { if (field.Name.Equals(key) && field.CanWrite) { object value = null; Type changedType = !field.PropertyType.IsGenericType ? field.PropertyType : Nullable.GetUnderlyingType(field.PropertyType); value = string.IsNullOrEmpty(data[key]) ? null : Convert.ChangeType(data[key], changedType); field.SetValue(model, value, null); } } } return(model); }
public void ToDictionary() { var @this = new global::System.Collections.Specialized.NameValueCollection { { "Fizz", "Buzz" } }; var result = @this.ToDictionary(); Assert.AreEqual("Buzz", result["Fizz"]); }
protected override bool LoadPostData (string postDataKey, global::System.Collections.Specialized.NameValueCollection postCollection) { if (WebTest.CurrentTest.UserData == null) { ArrayList list = new ArrayList (); list.Add ("LoadPostData"); WebTest.CurrentTest.UserData = list; } else { ArrayList list = WebTest.CurrentTest.UserData as ArrayList; if (list == null) throw new NullReferenceException (); list.Add ("LoadPostData"); WebTest.CurrentTest.UserData = list; } return base.LoadPostData (postDataKey, postCollection); }
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.Length != 0) { attr = fieldAttrs[0]; value = form["field_" + pro.Name] ?? (form[pro.Name] ?? ""); proType = pro.PropertyType; object obj; try { obj = ICollectionExtensions.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); }
private static string dumpCollectionValues(global::System.Collections.Specialized.NameValueCollection c) { var sb = new StringBuilder(); return(sb.ToString()); }