在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP