要获取或设置ArrayList中指定索引处的元素,代码如下-
using System;
using System.Collections;
public class Demo {
   public static void Main() {
      ArrayList arrList = new ArrayList();
      arrList.Add("Laptop");
      arrList.Add("Desktop");
      arrList.Add("Notebook");
      arrList.Add("Ultrabook");
      arrList.Add("Tablet");
      arrList.Add("Headphone");
      arrList.Add("Speaker");
      Console.WriteLine("Elements in ArrayList...");
      foreach(string str in arrList) {
         Console.WriteLine(str);
      }
      Console.WriteLine("Element at index 5 = " + arrList[5]);
   }
}输出结果
这将产生以下输出-
Elements in ArrayList... Laptop Desktop Notebook Ultrabook Tablet Headphone Speaker Element at index 5 = Headphone
让我们看另一个例子-
using System;
using System.Collections;
public class Demo {
   public static void Main() {
      ArrayList arrList = new ArrayList();
      arrList.Add("Laptop");
      arrList.Add("Desktop");
      arrList.Add("Notebook");
      arrList.Add("Ultrabook");
      arrList.Add("Tablet");
      arrList.Add("Headphone");
      arrList.Add("Speaker");
      Console.WriteLine("Elements in ArrayList...");
      foreach(string str in arrList) {
         Console.WriteLine(str);
      }
      Console.WriteLine("Element at index 5 = " + arrList[5]);
      arrList[5] = "SSD";
      Console.WriteLine("Element at index 5 (Updated) = " + arrList[5]);
   }
}输出结果
这将产生以下输出-
Elements in ArrayList... Laptop Desktop Notebook Ultrabook Tablet Headphone Speaker Element at index 5 = Headphone Element at index 5 (Updated) = SSD