下面的代碼示例創(chuàng)建一個 ArrayList 并添加多個項。該示例演示如何使用 Item 屬性(在 C# 中為索引器)訪問元素,并通過為指定索引的 Item 屬性賦新值來更改該元素。該示例還演示 Item 屬性不能用于在列表的當(dāng)前大小之外訪問或添加元素。
Imports SystemImports System.CollectionsImports Microsoft.VisualBasicPublic Class ExamplePublic Shared Sub Main' Create an empty ArrayList, and add some elements.Dim stringList As New ArrayListstringList.Add("a")stringList.Add("abc")stringList.Add("abcdef")stringList.Add("abcdefg")' Item is the default property, so the property name is' not required.Console.WriteLine("Element {0} is ""{1}""", 2, stringList(2))' Assigning a value to the property changes the value of' the indexed element.stringList(2) = "abcd"Console.WriteLine("Element {0} is ""{1}""", 2, stringList(2))' Accessing an element outside the current element count' causes an exception. The ArrayList index is zero-based,' so the index of the last element is (Count - 1).Console.WriteLine("Number of elements in the list: {0}", _stringList.Count)TryConsole.WriteLine("Element {0} is ""{1}""", _stringList.Count, _stringList(stringList.Count))Catch aoore As ArgumentOutOfRangeExceptionConsole.WriteLine("stringList({0}) is out of range.", _stringList.Count)End Try' You cannot use the Item property to add new elements.TrystringList(stringList.Count) = "42"Catch aoore As ArgumentOutOfRangeExceptionConsole.WriteLine("stringList({0}) is out of range.", _stringList.Count)End TryConsole.WriteLine()For i As Integer = 0 To stringList.Count - 1Console.WriteLine("Element {0} is ""{1}""", i, stringList(i))NextConsole.WriteLine()For Each o As Object In stringListConsole.WriteLine(o)NextEnd SubEnd Class'' This code example produces the following output:''Element 2 is "abcdef"'Element 2 is "abcd"'Number of elements in the list: 4'stringList(4) is out of range.'stringList(4) is out of range.''Element 0 is "a"'Element 1 is "abc"'Element 2 is "abcd"'Element 3 is "abcdefg"''a'abc'abcd'abcdefg
If you believe an article violates your rights or the rights of others, please
contact us.
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。