代码之家  ›  专栏  ›  技术社区  ›  Anthony Atmaram

TryParse(String,Int32)在失败时是否更改int参数?

  •  3
  • Anthony Atmaram  · 技术社区  · 14 年前

    出于兴趣,假设 Int32.TryParse(String, Int32)

    int type;
    if (!int.TryParse(someString, out type))
        type = 0;
    

    或者

    int type = 0;
    int.TryParse(someString, out type);
    
    4 回复  |  直到 14 年前
        1
  •  9
  •   Joel Coehoorn    14 年前

    这个 documentation

    如果转换成功,则包含与s中包含的数字等效的32位有符号整数值;如果转换失败,则包含零。

        2
  •  7
  •   SLaks    14 年前

    TryParse 0 .

    out 参数,即使失败,它也不可能在不设置值的情况下返回。

        3
  •  2
  •   MikeP    14 年前

    在执行其他操作之前,TryParse会将结果设置为0。因此,您应该使用第一个示例来设置默认值。

        4
  •  1
  •   Michael Goldshteyn    14 年前

    int type;
    
    if (int.TryParse(someString, out type)) 
      ; // Do something with type
    else 
      ; // type is set to zero, do nothing