如何在 C# 中声明和初始化列表?

csharpprogrammingserver side programming更新于 2025/5/30 17:07:17

要在 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() {
      // 初始化集合
      List<string> myList = new List<string>() {
         "one",
         "two",
         "three",
         "four",
         "five",
         "size"
      };
      Console.WriteLine(myList.Count);
   }
}

输出

6

相关文章