在 C# 中獲取或設定 ArrayList 中指定索引處的元素


以下為在 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

更新於:10-12-2019

848 次瀏覽

開啟你的 職業生涯

透過完成課程來取得認證

開始
廣告
© . All rights reserved.