使用以下代码段
Foo = IIf(String.IsNullOrEmpty(txtFoo.Text), 0, Integer.Parse(txtFoo.Text.Trim))
当我提交没有值的字段时出现错误:“输入字符串的格式不正确。” 我没有任何空间或其他东西,并且 String.IsNullOrEmpty(txtFoo.Text) 返回 true。怎么了?谢谢你。
IIF will evaluate:
Integer.Parse(txtFoo.Text.Trim)
irrespective of whether:
String.IsNullOrEmpty(txtFoo.Text)
is true or not (as it is just a function with three arguments passed to it, so all arguments must be valid). So even if txtFoo.text is empty
, it's still trying to Parse it to an Integer in this case.
If you're using VS2008, you can use the IF operator instead which will short-circuit as you're expecting IIF to do.
IIf is a function call rather than a true conditional operator, and that means both arguments have to be evaluated. Thus, it just attempts to call Integer.Parse() if your string is Null/Nothing.
If you're using Visual Studio 2008 or later, it's only a one character difference to fix your problem:
Foo = If(String.IsNullOrEmpty(txtFoo.Text), 0, Integer.Parse(txtFoo.Text.Trim())
This version of the If
keyword is actually a true conditional operator that will do the short-circuit evaluation of arguments as expected.
If you're using Visual Studio 2005 or earlier, you fix it like this:
If String.IsNullOrEmpty(txtFoo.Text) Then Foo = 0 Else Foo = Integer.Parse(txtFoo.Text.Trim())
IIf is not a true ternary operator, it actually evaluates both parameter expressions. You probably want to use the If operator instead (VS 2008+).
You'd simply say
If(String.IsNullOrEmpty(txtFoo.Text), 0, Integer.Parse(txtFoo.Text.Trim()))
条件部分和“else”部分之间的一个区别是字符串的修剪。您可以在调用之前尝试修剪字符串IsNullOrEmpty
。
Foo = IIf(String.IsNullOrEmpty(txtFoo.Text.Trim), 0, Integer.Parse(txtFoo.Text.Trim))