为什么Integer.TryParse在失败时将结果设置为零? [英] Why does Integer.TryParse set result to zero on failure?

查看:137
本文介绍了为什么Integer.TryParse在失败时将结果设置为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我有一个默认值为-1的整数,如果解析失败,我希望保持为-1。但是,无法解析的Integer.TryParse()函数将此默认值更改为零。

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

然而它输出:

defaultValue 0
parseSuccess False

我的理解是否正确?

推荐答案

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

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.

另一种方法是将其设为 ref 参数r并且只设置成功,但这意味着强制调用者首先初始化变量,即使他们没有想要这种行为。

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

这篇关于为什么Integer.TryParse在失败时将结果设置为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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