3

これを行うことの違いは何ですか:

Dim strTest As String
If strTest > " " Then

End If

この:

Dim strTest As String
If strTest <> "" Then

End If

コード例 1 は ASCII 値を比較していると思います (SPACE の ASCII コードは 32 です)。MSDN の String セクションを調べましたが、答えが見つかりません。

アップデート

ここで何が起こるかについても混乱しています:

 Dim strTest As String = "Test"
  If strTest > " " Then

  End If
4

1 に答える 1

1

The > (greater than) operator will test by alphabetical order or character code value order (depending on the Option Compare setting), whereas the <> (not equal) operator tests for equality. As long as the two strings are different at all, then <> will always evaluate to True. > will evaluate to true as long as the string on the right side of the operator comes after the first string alphabetically, or by character code value. Therefore:

Option Compare Text  ' Compare strings alphabetically

...

Dim x As String = "Hello"
Dim y As String = "World"

If x <> y Then
    ' This block is executed because the strings are different
Else
    ' This block is skipped
End If

If x > y Then
    ' This block is skipped
Else
    ' This block is executed because "Hello" is less than "World" alphabetically
End If

In your question, however, you are comparing a null string variable (set to Nothing) with an empty string. In that case, the comparison operators treat a null variable as an empty string. Therefore, Nothing <> "" should evaluate to False because both sides of the operator are considered empty strings. An empty or null string should always be considered the first in the sort order, so Nothing > "Hello" should evaluate to False because an empty string comes before everything else. But, Nothing > "" should evaluate to False because they are both equal and therefore neither comes before or after the other.

To answer you final question, "Test" > " " will test if the letter T comes before or after a space. If Option Compare is set to Text, it will compare them alphabetically and should return True (this ultimately depends on the alphabetic sorting for your locale). If Option Compare is set to Binary, it will compare them based on their character code values. If they are ASCII strings, a space character has a lower value than a letter, like T, so it, also, should return True.

于 2012-08-18T19:06:52.850 に答える