开发者

VB.NET: Comparing an object to a string literal

开发者 https://www.devze.com 2023-02-08 15:12 出处:网络
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

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:

  1. If myObject = "Hello World" Then ... -- won't compile
  2. If myObject Is "Hello World" Then ... -- tests for reference equality, which is just wrong
  3. If myObject.Equals("Hello World") Then ... -- throws an exception if myObject is Nothing
  4. If 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号