【问题标题】:how can i change queryString value to (int) [duplicate]我如何将queryString值更改为(int)[重复]
【发布时间】:2012-11-17 06:42:02
【问题描述】:

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

如何将 queryString 值更改为 (int)

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

【问题讨论】:

  • 亲爱的,在问任何问题之前先使用谷歌:)

标签: c# int


【解决方案1】:

使用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
}

【讨论】:

  • TryParse() +1,永远不要相信用户输入。
【解决方案2】:

用这个替换

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

【讨论】:

    【解决方案3】:
    int id = Convert.ToInt32(str_id, CultureInfo.InvariantCulture);
    

    【讨论】:

      【解决方案4】:

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

      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
      

      【讨论】:

        【解决方案5】:

        你必须使用int.Parse(str_id)

        编辑:不信任用户输入

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

        【讨论】:

          猜你喜欢
          • 2018-02-04
          • 2019-06-30
          • 1970-01-01
          • 1970-01-01
          • 2019-08-14
          • 1970-01-01
          • 2016-07-08
          • 1970-01-01
          • 2020-10-17
          相关资源
          最近更新 更多