C# 如何将queryString值更改为(int)

C# 如何将queryString值更改为(int),c#,int,C#,Int,可能重复: 如何将queryString值更改为(int) 换成这个 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); 您必须使用int.Parse(str\u id) 编辑:不信任用户输入

可能重复:

如何将queryString值更改为(int)

换成这个

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);

您必须使用
int.Parse(str\u id)

编辑:不信任用户输入

最好在解析之前检查输入是否为数字,因为此用法用于安全地获取
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
}

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

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

+1对于
TryParse()
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