如何在 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+ 查看次数

开启您的 职业

通过完成课程以获得证书

开始
广告