每次我们都通过Request[]取值去和当前实体赋值,很麻烦很烦琐..
写了一个公共的函数来取代这一功能,给大家探讨一下....
主要是通过反射来完成一个自动创建对象,赋值的的过程
具体代码如下是
- /// <summary>
- /// 利用反射对传过来的类型创建实例,且对实例复制
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <returns></returns>
- protected T InvokeGetFromRequest<T>()
- {
- Type type = typeof(T);
- object o = Activator.CreateInstance(type);
- PropertyInfo[] propertyInfos = type.GetProperties();
- string[] allKeys = Request.Params.AllKeys.Where(k => propertyInfos.Select(p => p.Name).ToArray<string>().Contains(k)).ToArray();
- foreach (string s in allKeys)
- {
- TypeForInvoke(propertyInfos.Where(p => p.Name == s).FirstOrDefault(), s, o);
- }
- return (T)o;
- }
- /// <summary>
- /// 对类型进行判断,这样就可以
- /// </summary>
- /// <param name="propertyInfo"></param>
- /// <param name="key"></param>
- /// <param name="o"></param>
- private void TypeForInvoke(PropertyInfo propertyInfo,string key,object o)
- {
- if (propertyInfo == null)
- return;
- string str = propertyInfo.PropertyType.FullName;
- if (str.Contains("System.Decimal"))
- {
- propertyInfo.SetValue(o, BillsUntily.GetDecimalTime(Request[key]), null);
- }
- else if (str.Contains("System.Int"))
- {
- propertyInfo.SetValue(o, BillsUntily.GetInt(Request[key]), null);
- }
- else if (str.Contains("System.DateTime"))
- {
- propertyInfo.SetValue(o, BillsUntily.GetDateTime(Request[key],propertyInfo), null);
- }
- else if (str.Contains("System.Double"))
- {
- propertyInfo.SetValue(o, BillsUntily.GetDoubleTime(Request[key]), null);
- }
- else
- {
- propertyInfo.SetValue(o, Request[key], null);
- }
- }
-------------------------------------------------------------
可以通过
User user = this.InvokeGetFromRequest<User>();
直接调用,这个实体已经被创建好,且已经赋值...