vb.net 数组变量中的项目总数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3936310/
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
Total Nos. of items in array variable
提问by Furqan Sehgal
I have an array variable (string type). It contains certain no. of items, that I donot know how many they are. I need to run a loop for that many nos. that the array contains. I tried LBound and UBound loop but it says my array is not a system array. How can I know how many items my array contains?
我有一个数组变量(字符串类型)。它包含某些没有。的项目,我不知道它们有多少。我需要为那么多号码运行一个循环。数组包含的。我尝试了 LBound 和 UBound 循环,但它说我的阵列不是系统阵列。我怎么知道我的数组包含多少个项目?
Thanks Furqan
谢谢富尔坎
回答by Oded
You can use the Length
property of the array object.
您可以使用Length
数组对象的属性。
From MSDN(Array.Length Property):
来自MSDN(Array.Length 属性):
Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array.
获取一个 32 位整数,该整数表示 Array 的所有维度中元素的总数。
Read about arrays in VB.NETand the Arrayclass for better understanding of arrays in VB.NET and the .NET framework.
阅读VB.NET 中的数组和Array类,以便更好地理解 VB.NET 和 .NET 框架中的数组。
Update:
更新:
However, for looping over an array you should simply use a For Each
loop (as an array is treated like any other collection in .NET) - this way you will not make any silly mistakes with array bounds and off by ones:
但是,对于数组循环,您应该简单地使用For Each
循环(因为数组被视为 .NET 中的任何其他集合) - 这样您就不会在数组边界和关闭边界方面犯任何愚蠢的错误:
For Each item As arrayItemType in MyArray
' do stuff with item
Next
See the example on thispage.
请参阅此页面上的示例。
回答by DOK
回答by schwindelig
Like Oded said, you can use the Length-propery of the Array. This would look something like this:
就像 Oded 说的,你可以使用数组的 Length 属性。这看起来像这样:
Dim data As String() = {"one", "two", "three", "four"}
For i = 0 To data.Length - 1
Console.WriteLine(data(i))
Next
If you just want to loop all strings in your array, you can use For Each as well:
如果您只想循环数组中的所有字符串,也可以使用 For Each :
For Each s As String In data
Console.WriteLine(s)
Next
回答by Mike Hofer
If the compiler is telling you that your variable is not a system array, then chances are, it's not an array. If it's not an array, you won't be able to get its bounds through any means.
如果编译器告诉您变量不是系统数组,那么很有可能它不是数组。如果它不是数组,您将无法通过任何方式获得它的边界。
Inspect the variable in the locals window and verify that your variable is of the type that you think it is. It's probably not an array after all.
检查局部变量窗口中的变量并验证您的变量是否为您认为的类型。毕竟它可能不是一个数组。