2009-08-07 19 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"; 
}