gpt4 book ai didi

.net - 如何避免评估所有 'iif' 表达式?

转载 作者:行者123 更新时间:2023-12-05 08:44:17 28 4
gpt4 key购买 nike

在 VB.NET 2005 中,有没有办法在尝试将空字符串转换为整数时抛出 无效转换异常 来执行以下操作?

Dim strInput As String = String.Empty
Dim intResult As Integer = IIf(IsNumeric(strInput), CInt(strInput), 100)

最佳答案

VB.NET 现在有一个真正的三元运算符(2008 年之后)

Dim intResult = If(IsNumeric(strInput), CInt(strInput), 100)

这与 IIF 不同,因为它使用短路评估。
如果测试表达式的计算结果为真,则 FalsePart 将被忽略,反之亦然

正如 Marek Kembrowsky 先生在其评论中所说,IIF 是一个函数,其参数在传入之前都经过评估,而 IF(作为三元运算符)是 VB 编译器的附加功能。

但是,当我在 VB.NET 中编程时,我不喜欢使用 Microsoft.VisualBasic 兼容性命名空间提供的快捷方式。该框架提供了更好的解决方案,例如 TryParse 方法集。如果输入字符串超过 Integer.MaxValue,您的示例将失败。

更好的方法是

Dim d As decimal
if Not Decimal.TryParse(strInput, d) then d = 100

或者,如果你有一个 float string(?好吧好吧,你已经明白我的意思了)

Dim d As Double
if Not Double.TryParse(strInput, d) then d = 100

关于.net - 如何避免评估所有 'iif' 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13494245/

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