Int32.TryParse()在失败时返回零 - 成功还是失败? [英] Int32.TryParse() returns zero on failure - success or failure?

查看:143
本文介绍了Int32.TryParse()在失败时返回零 - 成功还是失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从msdn读到这个关于 Int32.TryParse()

I read this from msdn about Int32.TryParse()


此方法返回,如果
转换成功,则包含
32位有符号整数值,相当于
到s中包含的数字,如果
转换失败,则包含零。

When this method returns, contains the 32-bit signed integer value equivalent to the number contained in s, if the conversion succeeded, or zero if the conversion failed.

但是如果传递的字符串本身是字符串表示'0'会发生什么。所以 TryParse 将返回零。我怎么知道它是成功还是失败?

But what happens if the passed string itself is a string representation of '0'. So the TryParse will return zero. How can I know if it is a success or a failure?

推荐答案

不, TryParse 返回 true或false表示成功。 out 参数的值用于解析的值,或者在失败时使用0。所以:

No, TryParse returns true or false to indicate success. The value of the out parameter is used for the parsed value, or 0 on failure. So:

int value;
if (Int32.TryParse(someText, out value))
{
    // Parse successful. value can be any integer
}
else
{
    // Parse failed. value will be 0.
}

所以如果你传入0,它将会执行第一个块,而如果你传入坏号码,它将执行第二个块。

So if you pass in "0", it will execute the first block, whereas if you pass in "bad number" it will execute the second block.

这篇关于Int32.TryParse()在失败时返回零 - 成功还是失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆