C# 填充客户端提交的值到T对象
程序员文章站
2022-04-09 08:39:21
/// /// 填充客户端提交的值到 T 对象 如appinfo = AppConvert.To(context.Request.Form); /// /// 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; }
上一篇: php 高性能书写