2009-08-07 18 views
2

有没有更好的方法,然后try/catch解析数字和日期时间没有崩溃的页面?asp.net c#更好的方法来解析查询字符串的数字和日期时间,然后尝试/ catch

如果它们不是有效的数字/日期时间,它们应该为空。

这里是我到目前为止有:

long id = null; 
try{ 
    id = Int64.Parse(Request.QueryString["id"]); 
}catch(Exception e){} 

DateTime time = null; 
try{ 
    time = DateTime.Parse(Request.QueryString["time"]); 
}catch(Exception e){} 

+0

哦,好吧,我不能相信我错过了TryParse ..... 我一直在拉着一个全能的,现在很漂亮,谢谢! – Fox 2009-08-07 19:57:02

回答

14
int tempInt = 0; 
if(int.TryParse(Request["Id"], out tempInt)) 
    //it's good!! 

同样,日期是 “DateTime.TryParse”

编辑

要充分模仿你的代码在做什么,你会有这样的:

long? id = null; DateTime? time = null; 
long tempLong; DateTime tempDate; 

if(long.TryParse(Request["id"], out tempLong)) 
    id = tempLong; 
if(DateTime.TryParse(Request["time"], out tempDate)) 
    time = tempDate; 
3

使用TryParse代替Parse。

TryParse不会抛出,对于这样的情况非常有用,其中输入不一定是可信的,而且您不希望抛出异常。

1

你注意到了TryParse?

long id = -1; 
if(Int64.TryParse(Request.QueryString["id"] ?? "", out id)) 
    // is valid... 
0

这是怎么我通常在我的项目:

public long? ClientId 
    { 
     get 
     { 
      long? result = null; 
      if (Request.QueryString[QueryStringConstants.ClientId] != null) 
       result = Convert.ToInt64(Request.QueryString[QueryStringConstants.ClientId]); 

      return result; 
     } 
    } 


    public DateTime? ItemPurchasedDate 
    { 
     get 
     { 
      DateTime? result = null; 
      if (Request.QueryString[QueryStringConstants.ItemPurchasedDate] != null) 
       result = Convert.ToDateTime(Request.QueryString[QueryStringConstants.ItemPurchasedDate]); 

      return result; 
     } 
    } 

而且我确定我的静态类QueryStringConstants像这样

public static class QueryStringConstants 
{ 
public static string ClientId = "clientId"; 
public static string ItemPurchasedDate = "itemPurchasedDate"; 
}