C# 中的集合初始化


使用集合初始化器语法来初始化类对象之类的集合。

首先,为 Employee 对象设置值 -

var emp1 = new Employee() { EID = 001, EmpName = "Tim", EmpDept = "Finance"};
var emp2 = new Employee() { EID = 002, EmpName = "Tom", EmpDept = "HR"};

现在在集合下添加此内容。

IList<Employee> empDetails = new List<Employee> {emp1, emp2 };

让我们看看完整的代码 -

示例

 现场演示

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      var emp1 = new Employee() { EID = 001, EmpName = "Tim", EmpDept = "Finance"};
      var emp2 = new Employee() { EID = 002, EmpName = "Tom", EmpDept = "HR"};
      IList<Employee> empDetails = new List<Employee> {emp1, emp2 };

      // Employee 1
      Console.WriteLine("Employee One...");
      Console.WriteLine(emp1.EID);
      Console.WriteLine(emp1.EmpName);
      Console.WriteLine(emp1.EmpDept);

      // Employee 2
      Console.WriteLine("Employee Two...");
      Console.WriteLine(emp2.EID);
      Console.WriteLine(emp2.EmpName);
      Console.WriteLine(emp2.EmpDept);
   }
}

public class Employee {
   public int EID { get; set; }
   public string EmpName { get; set; }
   public string EmpDept { get; set; }
}

输出

Employee One...
1
Tim
Finance
Employee Two...
2
Tom
HR

更新于: 23-Jun-2020

745 次观看

开启你的 职业生涯

通过完成课程获取认证

立即开始
广告