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

时间:2010-10-31 23:52:23

标签: .net tryparse

出于兴趣,可以安全地假设如果Int32.TryParse(String, Int32)失败,那么int参数将保持不变?例如,如果我希望我的整数具有默认值,那将更明智?

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

OR

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

4 个答案:

答案 0 :(得分:9)

documentation有答案:

  

包含等于s中包含的数字的32位有符号整数值(如果转换成功),或者如果转换失败则为零。

答案 1 :(得分:7)

TryParse会将其设为0

由于它是out参数,因此即使在失败时也不可能在没有设置值的情况下返回。

答案 2 :(得分:2)

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

答案 3 :(得分:1)

如果失败,则返回false并将type设置为零。这将是最明智的,因此:

int type;

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