为什么 Integer.TryParse 在失败时将结果设置为零?

发布于 2024-07-26 05:49:06 字数 560 浏览 1 评论 0原文

我对 Integer.TryParse() 函数的理解是,它尝试从传入的字符串中解析整数,如果解析失败,结果整数将保持像以前一样。

我有一个默认值为 -1 的整数,如果解析失败,我希望将其保留为 -1。 然而,解析失败时的 Integer.TryParse() 函数会将此默认值更改为零。

Dim defaultValue As Integer = -1
Dim parseSuccess As Boolean = Integer.TryParse("", defaultValue)
Debug.Print("defaultValue {0}", defaultValue)
Debug.Print("parseSuccess {0}", parseSuccess)

我的期望是上面的代码片段应该输出:

defaultValue -1
parseSuccess False

但是它输出:

defaultValue 0
parseSuccess False

我的理解正确吗?

My understanding of the Integer.TryParse() function was that it tried to parse an integer from the passed in string and if the parse failed the result integer would remain as it did before.

I have an integer with a default value of -1 which I would like to remain at -1 if the parse fails. However the Integer.TryParse() function on failing to parse is changing this default value to zero.

Dim defaultValue As Integer = -1
Dim parseSuccess As Boolean = Integer.TryParse("", defaultValue)
Debug.Print("defaultValue {0}", defaultValue)
Debug.Print("parseSuccess {0}", parseSuccess)

My expectation is that the code snippet above should output:

defaultValue -1
parseSuccess False

However instead it outputs:

defaultValue 0
parseSuccess False

Is my understanding correct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

红颜悴 2024-08-02 05:49:06

它是一个 out 参数,这意味着它必须由方法设置(除非它抛出异常) - 该方法无法看到原始值是什么。

另一种方法是使其成为 ref 参数,并仅在成功时设置它,但这意味着强制调用者首先初始化该变量,即使他们想要这种行为。

不过,您可以编写自己的实用方法:

public bool TryParseInt32(string text, ref int value)
{
    int tmp;
    if (int.TryParse(text, out tmp))
    {
        value = tmp;
        return true;
    }
    else
    {
        return false; // Leave "value" as it was
    }
}

It's an out parameter, which means it must be set by the method (unless it throws an exception) - the method can't see what the original value was.

The alternative would have been to make it a ref parameter and only set it on success, but that would mean forcing callers to initialize the variable first even if they didn't want this behaviour.

You can write your own utility method though:

public bool TryParseInt32(string text, ref int value)
{
    int tmp;
    if (int.TryParse(text, out tmp))
    {
        value = tmp;
        return true;
    }
    else
    {
        return false; // Leave "value" as it was
    }
}
恬淡成诗 2024-08-02 05:49:06

你是对的,TryParse 如果失败则使用 0。 (MSDN说的很清楚了)
但如果您想要的话,您可以检查 paseSuccess 并返回默认值。

You are correct, TryParse uses 0 if it fails. (MSDN says this quite clearly)
But you could check paseSuccess and return your default value if this is what you want to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文