VB.NET 数组包含方法不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19056967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET Array Contains method does not work
提问by Art F
In VB.NET I am trying to determine in a given string exists in a String Array. According to my research the Array has a 'Contains' method that I can use, so the Code looks something like this:
在 VB.NET 中,我试图确定在给定的字符串中是否存在于字符串数组中。根据我的研究,数组有一个我可以使用的“包含”方法,所以代码看起来像这样:
Dim fileTypesZ As String() = {"PDF", "TXT", "DOC", "DOCX", "XLS", "XLSX", "JPG", "JPGE", "BMP", "GIF"}
If (fileTypesZ.Contains(tempTest)) Then
End If
However, VB.NET is saying 'Contains' is not a member of 'System.Array'. Is there another method that I can use?
但是,VB.NET 说“Contains”不是“System.Array”的成员。我可以使用另一种方法吗?
回答by Reed Copsey
There is no Containson Array, but there is Enumerable.Contains, which is an extension method that works on arrays.
没有Containson Array,但有Enumerable.Contains,这是一种适用于数组的扩展方法。
Make sure to include Imports System.Linqat the top of your file, and that you're referencing System.Core.dllin your project references.
确保包含Imports System.Linq在文件的顶部,并且System.Core.dll在项目引用中引用。
回答by Jason Hughes
What framework are you working with? I ran this in 4 Full and it worked:
你在使用什么框架?我在 4 Full 中运行了它并且它起作用了:
Sub Main()
Dim fileTypesZ As String() = {"PDF", "TXT", "DOC", "DOCX", "XLS", "XLSX", "JPG", "JPGE", "BMP", "GIF"}
If (fileTypesZ.Contains("PDF")) Then
MsgBox("Yay")
End If
End Sub
Keep in mind array.contains uses equality, so "PDF" works, "PD" does not. You may need to iterate with indexof if you are looking for partial matches.
请记住 array.contains 使用相等,因此“PDF”有效,“PD”无效。如果您正在寻找部分匹配,您可能需要使用 indexof 进行迭代。
In that case try: Dim fileTypesZ As String() = {"PDF", "TXT", "DOC", "DOCX", "XLS", "XLSX", "JPG", "JPGE", "BMP", "GIF"}
在这种情况下尝试: Dim fileTypesZ As String() = {"PDF", "TXT", "DOC", "DOCX", "XLS", "XLSX", "JPG", "JPGE", "BMP", "动图"}
If (fileTypesZ.Contains("PD")) Then
MsgBox("Yay")
Else
For i = 0 To fileTypesZ.Length - 1
If fileTypesZ(i).IndexOf("PD") = 0 Then
MsgBox("Yay")
End If
Next
End If

