C# 填充客户端提交的值到T对象

/// <summary>
     /// 填充客户端提交的值到 T 对象  如appinfo = AppConvert.To<Appinfo>(context.Request.Form);
     /// </summary>
     /// <typeparam name="T">T 类</typeparam>
     /// <param name="datas">客户端提交的值</param>
     /// <returns>T 对象</returns>
     public static T To<T>(NameValueCollection datas) where T : class, new()
     {
         Type type = typeof(T);
         string[] strArray = type.FullName.Split(new char[] { '.' });
         string str = strArray[strArray.Length - 1];
         PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
         T local = Activator.CreateInstance<T>();
         foreach (string str2 in datas.AllKeys)
         {
             string str3 = datas[str2];
             if (!string.IsNullOrEmpty(str3))
             {
                 str3 = str3.TrimEnd(new char[0]);
             }
             foreach (PropertyInfo info in properties)
             {
                 string str4 = string.Format("{0}.{1}", str, info.Name);
                 if (str2.Equals(info.Name, StringComparison.CurrentCultureIgnoreCase) || str2.Equals(str4, StringComparison.CurrentCultureIgnoreCase))
                 {
                     string typeName = info.PropertyType.ToString();
                     if (info.PropertyType.IsGenericType)
                     {
                         typeName = info.PropertyType.GetGenericArguments()[0].ToString();
                     }
                     object nullInternal = GetNullInternal(info.PropertyType);
                     Type conversionType = Type.GetType(typeName, false);
                     if (!string.IsNullOrEmpty(str3))
                     {
                         nullInternal = Convert.ChangeType(str3, conversionType);
                     }
                     info.SetValue(local, nullInternal, null);
                 }
             }
         }
         return local;
     }
上一篇:c# 遍历属性


下一篇:C# 对象类型映射转换方法总结,表达式树实现高效转换