有没有比 try/catch 更好的方法来解析数字和日期时间而不会使页面崩溃?
如果它们不是有效的数字/日期时间,则它们应该为空。
这是我到目前为止所得到的:
long id = null;
尝试{
id = Int64.Parse(Request.QueryString["id"]);
} catch (异常 e){}
DateTime时间=空;
尝试{
time = DateTime.Parse(Request.QueryString["time"]);
} catch (异常 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;
关于c# - asp.net c# 从查询字符串中解析数字和日期时间的更好方法然后尝试/捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1246663/