为什么 Integer.TryParse 在失败时将结果设置为零?
我对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它是一个
out
参数,这意味着它必须由方法设置(除非它抛出异常) - 该方法无法看到原始值是什么。另一种方法是使其成为
ref
参数,并仅在成功时设置它,但这意味着强制调用者首先初始化该变量,即使他们不想要这种行为。不过,您可以编写自己的实用方法:
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:
你是对的,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.