从未知来源转换C#数据类型

Mar*_*rko 1 c# types

在将字符串(通常)转换为适当的数据类型时,似乎存在很多混淆,同时也在动态验证它.无论我在哪里 - 博客,文章,代码示例,论坛......一些人似乎有一种处理这些场景的首选方式.

案例通常是来自未知来源的字符串/对象,例如QueryString,Session/Viewstate,WebService等等......

我见过很多不同的例子:

假设我们正在尝试获取id=查询字符串并将其作为整数用于我们的代码中.但是有人篡改了我们的网址并将其更改为

http://www.example.com/page.aspx?id=sometextvalue

单程

int id = Convert.ToInt32(Request["id"]);
// "Input string was not in a correct format"
Run Code Online (Sandbox Code Playgroud)

其他方式

int id = (int)Request["id"];
// "Input string was not in a correct format"
Run Code Online (Sandbox Code Playgroud)

还有另一种方式

int id = int.Parse(Request["id"]);
// "Input string was not in a correct format"
Run Code Online (Sandbox Code Playgroud)

我见过这个 (并且抛出异常并通知用户是有意义的)

int id = 0;
try {
    id = Convert.ToInt32(Request["id"]);
}
catch(Exception ex) {
    lblError.Text = ex.Message;
}
if(id > 0) { ... }
Run Code Online (Sandbox Code Playgroud)

最后,和我个人使用的那个

int id = 0;
int.TryParse(Request["id"], out id);

// make sure it's not 0
if(id > 0) { // live a happy life }
Run Code Online (Sandbox Code Playgroud)

这同样适用于所有其他类型,bool,double,decimal等..

请帮助我了解正确的方法,因为我发现自己每天都在使用它.

Wes*_*ser 6

那么,对于初学者你应该使用:

int id;
if(!int.TryParse(Request["id"], out id)
    //notify the user, or handle it someother way
Run Code Online (Sandbox Code Playgroud)

而不是检查id> 0. 如果解析成功则int.TryParse(string, out int)返回true,false否则返回.

int.TryParse的MSDN文档(string,out int)