如何将queryString值更改为(int)

时间:2012-11-29 08:26:35

标签: c# int

  

可能重复:
  How can I convert String to Int?

如何将queryString值更改为(int)

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

5 个答案:

答案 0 :(得分:10)

使用Int32.TryParse Method安全获取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
}

答案 1 :(得分: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);

答案 2 :(得分:2)

int id = Convert.ToInt32(str_id, CultureInfo.InvariantCulture);

答案 3 :(得分: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

答案 4 :(得分:1)

你必须使用int.Parse(str_id)

修改:不信任用户输入

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