vb.net - 使用 Is 运算符比较循环中的字符串

标签 vb.net

Is 运算符在比较两个字符串时工作正常,例如:

Dim str1 As String = "TagnameX"
Dim str2 As String = "TagnameX"

Dim strChk as boolean = str1 Is str2
'strChk returns True

但是当 Substring 提取其中一个字符串时,它返回 false !如下:

Dim str1 As String = "t#1TagnameX"
Dim str1Extract As String = str1.Substring(3, 8)
Dim strArr() = {"Tagname1", "Tagname2", "TagnameX"}  

 For i = 0 To strArr.Length - 1
      If strArr(i) Is str1Extract Then
         MsgBox("TagnameX found!")
      else
         MsgBox("TagnameX was not found!")
      End If
 Next
'TagnameX was not found!

所以我在某些方面使用它是错误的吗?感谢您的帮助! :)

最佳答案

Is-operator返回两个引用是否相等:即两个变量是否引用内存中的同一位置。

第一个代码片段返回 True 因为对于文字字符串,.NET interns重复,而不是在内存中保留单独的相同副本,因此 str1str2 引用内存中的相同字符串。

第二个代码片段返回 False,因为 .NET 不一定保留中间字符串,例如 Substring 返回的字符串。因此变量 strstrExtract 并不引用同一个字符串。

您应该使用等于运算符=来比较两个字符串的值。

关于vb.net - 使用 Is 运算符比较循环中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60269602/

相关文章:

.net - 根据 Regex.Matches MatchCollection 替换字符串中的内容

.net - 如何在 VB.NET 中确定是否为 "object is IEnumerable"(C# 语法)?

asp.net - 如何修复 "' ddlAssignedTo' 的 SelectedValue 无效,因为它不存在于项目列表中

MySQL:创建表时出现语法错误

C# 到 VB.Net 的转换问题

c# - C# 中的 ProductName 和 CompanyName

c# - 从 .NET 2.0 应用程序调用 .NET 4.0 WPF 类库

mysql - 你调用的对象是空的

asp.net - 文件上传在 ASP.NET WebForm 中的 Microsoft IE 和 Microsoft Edge 浏览器中不起作用

c# - 需要一个通过 USB 端口控制的 Switch 组件