原由

经常遇到 int Age=Convert.ToInt32(this.txtAge.Text);

这种蛋疼的代码,特写次方法。

之所以抛出异常是希望知道转换失败,格式错误的属性是什么,方便调试。

新版本

//新版本,可以再globa.ascx里面设置开发模式
//以便于调试错误
//表单转实体对象V2版
public class HttpRequestHelper
{
/// <summary>
/// 开发模式,设置成开发模式后抛出异常,可查看出错的属性,和类型
/// </summary>
public static bool DevMode { get; set; }
#region 表单转换成实体模型
/// <summary>
/// 表单转换成实体模型
/// 用法:1、插入,先new一个对象传入;
/// 2、更新,先从数据库查出这个对象传入
/// </summary>
/// <param name="obj">泛型对象</param>
/// <returns></returns>
public static T ConvertForm2Model<T>(T obj)
{
if (null == obj)
{
obj = default(T);
obj = Activator.CreateInstance<T>();
}
Type type = typeof(T);
foreach (var p in type.GetProperties())
{
string result = HttpContext.Current.Request.Params[p.Name];
if (!string.IsNullOrWhiteSpace(result))
{
try
{
p.SetValue(obj, Convert.ChangeType(result, p.PropertyType), null);
}
catch(Exception ex)
{
if (DevMode)
{
throw new Exception("类型转换错误,变量:" + p.Name + ",类型:" + p.PropertyType + ",错误信息:" + ex.Message);
}
else
{
//记录日志。。。。 }
}
}
}
return obj; }
#endregion
}

旧版本

//////////////////
///各位有什么好想法,请给个建议
//460247986@qq.com
////////////////// public class HttpRequestHelper<T> where T : class,new()
{
#region 表单转换成实体模型
/// <summary>
/// 表单转换成实体模型
/// 用法:1、插入,先new一个对象传入;
/// 2、更新,先从数据库查出这个对象传入
/// </summary>
/// <param name="obj">泛型对象</param>
/// <returns></returns>
public static T ConvertForm2Model(T obj=null)
{
if (null == obj)
{
obj = default(T);
obj = Activator.CreateInstance<T>();
}
Type type = typeof(T);
foreach (var p in type.GetProperties())
{
string result = HttpContext.Current.Request.Params[p.Name];
if (!string.IsNullOrWhiteSpace(result))
{
try
{
p.SetValue(obj, Convert.ChangeType(result, p.PropertyType), null);
}
catch(Exception ex)
{
throw new Exception("类型转换错误,变量:" + p.Name + ",类型:" + p.PropertyType+",错误信息:" + ex.Message);
}
}
}
return obj; }
#endregion
}

最新文章

  1. I/O多路复用
  2. css 去除input 获取焦点的蓝色边框
  3. Educational Codeforces Round 7 F - The Sum of the k-th Powers 拉格朗日插值
  4. Linux系统编程(4)——文件与IO之ioctl函数
  5. hbase 二级索引创建
  6. 自己动手写CPU之第六阶段(2)——移动操作指令实现思路
  7. wIndows phone 7 解析Html数据
  8. 记录一下Fedora21下安装Foundation5遇到的问题[尚有遗留问题]
  9. POJ 3041 Asteroids(匈牙利+邻接表)
  10. php - preg_match
  11. word:Can&#39;t find the word document templant:WordToRqm.doc
  12. java学习笔记(详细)
  13. 老师博客copy
  14. PHP之十六个魔术方法
  15. Linux 重启nginx
  16. CentOS Tomcat启动 Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
  17. 使用sql获取primary key名称
  18. 使用HTML5开发离线应用 - cache manifest
  19. MFC中创建多线程
  20. JDK7 AutoCloseable

热门文章

  1. Hibernate 中 简便proxool连接池配置
  2. ETL作业调度软件TASKCTL4.1单机部署
  3. 一步一步学习Vue(十)
  4. 走进STM32世界之Hex程序烧写
  5. 初学django搭建一个通讯录应用
  6. Python学习——(1)Centos安装Flask
  7. kickstart自动化安装--tftp+nfs+dhcp
  8. Koa框架教程,Koa框架开发指南,Koa框架中文使用手册,Koa框架中文文档
  9. 字符串--hdu--3783--ZOJ
  10. 【python密码学编程】7.暴力破解凯撒加密法