VB.NET: Comparing an object to a string literal
This might just be a matter of taste, but I'm wondering if there's a "recommended" way to compare a variable of type Object
(which might be Nothing
or have a different dynamic type than String
) to a string literal in VB.NET.
The following options obviously won't work:
If myObject = "Hello World" Then ...
-- won't compileIf myObject Is "Hello World" Then ...
-- tests for reference equality, which is just wrongIf myObject.Equals("Hello World") Then ...
-- throws an exception if myObject is NothingIf DirectCast(myObject, String) = "Hello World" Then ...
-- throws an exception if myObject is not a str开发者_如何学运维ing
Thus, the only (simple, single-expression) solution I could find is to use
If "Hello World".Equals(myObject) Then ...
which looks a bit clumsy to me. Did I miss any obvious alternative, other than doing type checks or explicit checks for Nothing
?
(Of course, we're talking about Option Strict On
.)
How about this:
If TryCast(myObject, String) = "Hello World" Then
If myObject
is not a String, then TryCast
will return Nothing
.
Object.Equals("Hello World", myObject) -or- Object.Equals(myObject, "Hello World")
The former will unconditionally call "Hello World".Equals, while the latter will call MyObject.Equals if MyObject is non-null, or else return false (since the quoted literal isn't null).
Note that with properly-designed objects, both of the above should be equivalent, but it's possible that MyObject could have an Equals method which returns True when compared to the string "Hello World"; if it does, the second statement would return True while the first would return False.
How about the shared function on the string class
If String.Compare(Trycast(myObject, String), "Hello World") = 0 Then...
This will also return inequality if myObject is Nothing or is not a string.
精彩评论