1

次のスニペットで

Foo = IIf(String.IsNullOrEmpty(txtFoo.Text), 0, Integer.Parse(txtFoo.Text.Trim))

値のないフィールドを送信すると、「入力文字列の形式が正しくありませんでした」というエラーが表示されます。スペースなどはなく、 String.IsNullOrEmpty(txtFoo.Text) は true を返します。なにが問題ですか?ありがとうございました。

4

4 に答える 4

5

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.

于 2010-12-01T13:24:28.637 に答える
1

IIf は真の条件演算子ではなく関数呼び出しであるため、両方の引数を評価する必要があります。したがって、文字列が Null/Nothing の場合、Integer.Parse() を呼び出そうとします。

Visual Studio 2008 以降を使用している場合、問題を解決するのは 1 文字の違いだけです。

Foo = If(String.IsNullOrEmpty(txtFoo.Text), 0, Integer.Parse(txtFoo.Text.Trim())

このバージョンのIfキーワードは、実際には、期待どおりに引数の短絡評価を行う真の条件演算子です。

Visual Studio 2005 以前を使用している場合は、次のように修正します。

If String.IsNullOrEmpty(txtFoo.Text) Then Foo = 0 Else Foo = Integer.Parse(txtFoo.Text.Trim())
于 2010-12-01T13:25:17.310 に答える
1

IIf は真の三項演算子ではなく、実際には両方のパラメーター式を評価します。代わりに If 演算子を使用することをお勧めします (VS 2008+)。

あなたは単に言うだろう

If(String.IsNullOrEmpty(txtFoo.Text), 0, Integer.Parse(txtFoo.Text.Trim()))
于 2010-12-01T13:25:33.673 に答える
0

条件部分と「else」部分の違いの 1 つは、文字列のトリミングです。を呼び出す前に文字列をトリミングしてみてくださいIsNullOrEmpty

Foo = IIf(String.IsNullOrEmpty(txtFoo.Text.Trim), 0, Integer.Parse(txtFoo.Text.Trim))
于 2010-12-01T13:28:08.867 に答える