TryParse方法,不被人注意的好东西

在用Asp.net做网站中,为了防止sql注入,对于get得到的每个数字值都要对其进行类型检查
以前我是这样写的(C#)

if (!CheckNum(Request.Querying["ID"]))
{
  Response.Redirect(
"Index.aspx");
}


bool CheckNum(object o)
{
   
bool v=false;
   
if (o!=null && o.tostring!="")
   
{
     
if (正则表达式检查通过)
       v
=true;
   }

   
return v; 
}


现在知道了TryParse这个方法,于是乎对于上面的操作可以这样写了,而且效率也提高了很多

int ID;
if (!int.TryParse(Request.QueryString["ID"],out ID))
{
Response.Redirect(
"Index.aspx");
}


其意思就是如果判断Request.QueryString["ID"]是否为int型,如果返回True,则直接将其值赋给ID

原文地址:https://www.cnblogs.com/eoiioe/p/1136745.html