asp.net c#从查询字符串中解析数字和日期时间的更好方法,然后重试/catch

asp.net c#从查询字符串中解析数字和日期时间的更好方法,然后重试/catch,c#,asp.net,C#,Asp.net,有没有比try/catch更好的方法来解析数字和日期时间而不破坏页面 如果它们不是有效的数字/日期时间,则应为空 以下是我到目前为止得到的信息: long id = null; try{ id = Int64.Parse(Request.QueryString["id"]); }catch(Exception e){} DateTime time = null; try{ time = DateTime.Parse(Request.QueryString["time"]);

有没有比try/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){}

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;

使用TryParse而不是Parse


TryParse不会抛出异常,并且适用于这样的情况,即输入不一定受信任,并且您不希望抛出异常。

您注意到TryParse了吗

long id = -1;
if(Int64.TryParse(Request.QueryString["id"] ?? "", out id))
   // is valid...
您可以使用TryParse:


这是我在项目中通常做的事情:

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";
}

哦,好吧,我不敢相信我错过了特里帕斯。。。。。我已经开了一个通宵,现在心情很好,谢谢!