编程语言
首页 > 编程语言> > C# 填充客户端提交的值到T对象

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;
     }

标签:info,string,填充,C#,str2,strArray,str3,PropertyType,客户端
来源: https://www.cnblogs.com/fanying/p/10918945.html