獲取或設定 C# 程式碼中 Collection 中指定索引處的元素


獲取或設定 Collection 中指定索引處的元素,如下面的程式碼所示 −

示例

 即時演示

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main() {
      Collection<string> col = new Collection<string>();
      col.Add("Laptop");
      col.Add("Desktop");
      col.Add("Notebook");
      col.Add("Ultrabook");
      col.Add("Tablet");
      col.Add("Headphone");
      col.Add("Speaker");
      Console.WriteLine("Elements in Collection...");
      foreach(string str in col) {
         Console.WriteLine(str);
      }
      Console.WriteLine("Element at index 3 = " + col[3]);
      Console.WriteLine("Element at index 4 = " + col[4]);
   }
}

輸出

將生成以下輸出 −

Elements in Collection...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 3 = Ultrabook
Element at index 4 = Tablet

示例

讓我們看另一個示例 −

 即時演示

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main() {
      Collection<string> col = new Collection<string>();
      col.Add("Laptop");
      col.Add("Desktop");
      col.Add("Notebook");
      col.Add("Ultrabook");
      col.Add("Tablet");
      col.Add("Headphone");
      col.Add("Speaker");
      Console.WriteLine("Elements in Collection...");
      foreach(string str in col) {
         Console.WriteLine(str);
      }
      Console.WriteLine("Element at index 3 = " + col[3]);
      col[3] = "SSD";
      Console.WriteLine("Element at index 3 (Updated) = " + col[3]);
   }
}

輸出

將生成以下輸出 −

Elements in Collection...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 3 = Ultrabook
Element at index 3 (Updated) = SSD

更新於: 2019 年 12 月 10 日

202 次瀏覽

你的 職業生涯啟航

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.