开发者

How do I declare and access arrays in visual basic?

开发者 https://www.devze.com 2023-04-11 05:45 出处:网络
I declared an array of strings and initialized every element to \"5\". But when I debug with a breakpoint after the For-Each, all my array members have Nothing in them. I\'m on Visual Studio 2010. Hel

I declared an array of strings and initialized every element to "5". But when I debug with a breakpoint after the For-Each, all my array members have Nothing in them. I'm on Visual Studio 2010. Help ple开发者_如何转开发ase?

Dim words(999) As String

For Each word As String In words
    word = "5"
Next


What you have there is good for reading array's, but not for writing them. Your code translates to:

Create words array with 1000 elements
For each index in the array
    word = words(index)
    word = "5"
Next index

At no point does it put the word back into the array. The code is missing:

    ...
    words(index) = word
Next index

What you need to do is:

Dim words(999) As String

For index As Integer = 0 to words.Length - 1
    words(index) = "5"
Next

Edit: In response to the comment below.

Once you've initialised the array, you can use a For/Each loop to read the elements.

For Each word As String in words
    Console.WriteLine(word)
Next

This is the same as:

For index As Integer = 0 To words.Length - 1
    Console.WriteLine(words(index))
Next


You can also do this:

Dim Words() As String = Enumerable.Repeat("5", 1000).ToArray()
0

精彩评论

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