下面的代码示例创建一个 ArrayList 并添加多个项。该示例演示如何使用 Item 属性(在 C# 中为索引器)访问元素,并通过为指定索引的 Item 属性赋新值来更改该元素。该示例还演示 Item 属性不能用于在列表的当前大小之外访问或添加元素。
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.
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。