来源不明的转换C#数据类型 [英] Converting C# Data Types from unknown sources

查看:152
本文介绍了来源不明的转换C#数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎有很多混乱的周围将字符串转换(通常情况下)其相应的数据类型,同时验证它的飞行也是如此。无论我期待 - 博客,文章,代码示例,论坛..几人似乎有一个 首选处理这些场景的方式。

There seems to be a lot of confusion around converting strings (usually) to their appropriate datatype, whilst validating it on the fly as well. Wherever I look - blogs, articles, code samples, forums.. a few people seem to have a preferred way of dealing with these scenarios.

的情况下通常是一个字符串/对象来自未知来源,如查询字符串,会话/视图状态,WebService的,等等...

The case is usually a string/object that comes from an unknown source, such as QueryString, Session/Viewstate, WebService, and so on...

我见过很多不同的例子:

假设我们正在试图获得了 ID = 查询字符串,并用它在我们的代码为整数。但有人篡改了我们的网址,并将其改为

Say we're trying to get the id= Query String and use it in our code as an integer. But someone tampered with our URL and changed it to

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

单向

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



另一种方式

int id = (int)Request["id"];
// "Input string was not in a correct format"



然而,另一个方法

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



我有见过这个 (和它种有意义的抛出一个异常,并通知用户)

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



最后,也是一个我亲自使用

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

// make sure it's not 0
if(id > 0) { // live a happy life }

这也适用于所有其他类型,布尔双击小数等..

This goes for all the other types, bool, double, decimal and so on..

请帮助我理解正确的方法是什么,因为我发现自己使用这在某一天到一天的基础上

Please help me understand what the correct way is, as I find myself using this on a day-to-day basis.

推荐答案

嗯,首先你应该使用:

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

不是检查ID> 0 int.TryParse(字符串,OUT INT)收益真正如果解析成功,其他。

instead of checking for id > 0. int.TryParse(string, out int) returns true if the parse succeeded, false otherwise.

MSDN文档int.TryParse(字符串,OUT INT)

这篇关于来源不明的转换C#数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆