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

标签 c# asp.net

有没有比 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/

相关文章:

c# - 即使使用ConfigureAwait(false),异步代码也会死锁

c# - 在 ListView 中显示数据表中的图像

javascript - 在 ASP.NET 中为 html src 语句调用 C# 方法(输出字符串)

javascript - 如何检索函数输入 javascript

c# - WPF MVVM 登录凭据

c# - mailgun 到电子邮件地址替换为抄送电子邮件地址

c# - 使用委托(delegate)调用构造函数

asp.net - 如何在不访问代码的情况下将文档类型更改为标准模式?

asp.net - 如何找到 ASP.NET 应用程序中的 I/O 瓶颈

c# - 如何使用数据库逻辑添加自定义方法