如何在 C# 中宣告和初始化列表?


若要宣告和初始化 C# 中的列表,首先宣告列表 −

List<string> myList = new List<string>()

現在新增元素 −

List<string> myList = new List<string>() {
   "one",
   "two",
   "three",
};

透過此操作,我們在上面添加了六個元素。

以下是宣告和初始化 C# 中列表的完整程式碼 −

示例

 即時演示

using System;
using System.Collections.Generic;

class Program {
   static void Main() {
      // Initializing collections
      List<string> myList = new List<string>() {
         "one",
         "two",
         "three",
         "four",
         "five",
         "size"
      };
      Console.WriteLine(myList.Count);
   }
}

輸出

6

更新時間:20-Jun-2020

12K+ 檢視次數

開啟您的 職業

透過完成課程以獲得證書

開始
廣告