如何在 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-6-2020

12K+ 瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.