gpt4 book ai didi

.net - 使用 [Type].Parse 还是 C[Type] 更好

转载 作者:行者123 更新时间:2023-12-01 11:03:29 25 4
gpt4 key购买 nike

如果我尝试将字符串放入 bool 变量中,例如:

    Dim testValue As String = "True"
Dim bool1 As Boolean = testValue

Option Strict On我收到一个错误,建议的解决方法是将第二行更改为:
    Dim bool1 As Boolean = CBool(testValue)

这很好,但是 - 这样做的优点/缺点是什么:
    Dim bool1 As Boolean = Boolean.Parse(testValue)
CBool对我来说感觉非常喜欢 VB6,但我们应该使用哪个,为什么?

最佳答案

如果您在两种情况下都知道它是一个字符串,那么它应该是一个等效的过程。由于 Cbool 最终会调用一个函数来转换它。 (只要您的值是“真”或“假”)

如果您使用诸如 cbool(value) 之类的东西并且该值为 bool 值,则有所不同。

来自 MSDN :

Note that the parse operation succeeds only if the string to be parsed is "True" (the value of the TrueString field) or "False" (the value of the FalseString field) in a case-insensitive comparison.



来自 MSDN关于 Cbool(以及其他类似的方法):

These functions are compiled inline, meaning the conversion code is part of the code that evaluates the expression. Sometimes there is no call to a procedure to accomplish the conversion, which improves performance. Each function coerces an expression to a specific data type



所以,如果你使用 cbool(value) 如果你的值是一个 bool 值,它只使用它,不需要转换。这使得它可能更有效率。

你也可以看看这个:
Integer.Parse vs. CInt

关于.net - 使用 [Type].Parse 还是 C[Type] 更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8492468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com