4

可能重复:
如何将 String 转换为 Int?

如何将 queryString 值更改为 (int)

string str_id;
str_id = Request.QueryString["id"];
int id = (int)str_id;
4

5 回答 5

10

使用Int32.TryParse 方法安全地获取int值:

int id;
string str_id = Request.QueryString["id"];
if(int.TryParse(str_id,out id))
{
    //id now contains your int value
}
else
{
    //str_id contained something else, i.e. not int
}
于 2012-11-29T08:29:02.613 回答
3

换成这个

string str_id;
str_id = Request.QueryString["id"];
int id = Convert.ToInt32(str_id);

或者更简单、更有效的

string str_id;
str_id = Request.QueryString["id"];
int id = int.Parse(str_id);
于 2012-11-29T08:28:20.660 回答
2
int id = Convert.ToInt32(str_id, CultureInfo.InvariantCulture);
于 2012-11-29T08:29:15.203 回答
2

有几种方法可以做到这一点

string str_id = Request.QueryString["id"];

int id = 0;

//this prevent exception being thrown in case query string value is not a valid integer
Int32.TryParse(str_id, out id); //returns true if str_id is a valid integer and set the value of id to the value. False otherwise and id remains zero

其他

int id = Int32.Parse(str_id); //will throw exception if string is not valid integer
int id = Convert.ToInt32(str_id);  //will throw exception if string is not valid integer
于 2012-11-29T08:31:00.140 回答
1

你必须使用int.Parse(str_id)

编辑 :不要相信用户输入

最好在解析之前检查输入是否为数字,为此使用int.TryParse

于 2012-11-29T08:28:22.833 回答