C# 中的物件初始化程式


使用物件初始化對類的物件進行初始化。

使用它,你可以在建立物件時為欄位賦值。

我們建立了 Employee 物件,並使用大括號同時對值進行了賦值。

Employee empDetails = new Employee() {
   EID = 10,
   EmpName = "Tim",
   EmpDept = "Finance"
}

現在訪問 Employee 類的值。例如,對於員工的姓名。

empDetails.EmpName

我們來看一下完整程式碼 −

示例

 線上演示

using System;
public class Demo {
   public static void Main() {
      Employee empDetails = new Employee() {
         EID = 10,
         EmpName = "Tim",
         EmpDept = "Finance"
      };
      Console.WriteLine(empDetails.EID);
      Console.WriteLine(empDetails.EmpName);
      Console.WriteLine(empDetails.EmpDept);
   }
}

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

輸出

10
Tim
Finance

更新於: 2020 年 6 月 23 日

140 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.