C# 中的“this”關鍵字


C# 中的“this”關鍵字用於引用類的當前例項。如果方法引數和類欄位同名,它還可用於區分它們。

“this”關鍵字的另一種用法是從同一類的建構函式中呼叫另一個建構函式。

在此,我們以示例來演示如何在 C# 中使用“this”關鍵字 −

public Student(int id, String name, int age, String subject) {
   this.id = id;
   this.name = name;
   this.subject = subject;
   this.age = age;
} 

示例

讓我們來看一個完整的示例,瞭解如何在 C# 中使用“this”關鍵字 −

 即時演示

using System.IO;
using System;

class Student {
   public int id, age;  
   public String name, subject;

   public Student(int id, String name, int age, String subject) {
      this.id = id;
      this.name = name;
      this.subject = subject;
      this.age = age;
   }

   public void showInfo() {
      Console.WriteLine(id + " " + name+" "+age+ " "+subject);
   }
}

class StudentDetails {
   public static void Main(string[] args) {
      Student std1 = new Student(001, "Jack", 23, "Maths");
      Student std2 = new Student(002, "Harry", 27, "Science");
      Student std3 = new Student(003, "Steve", 23, "Programming");
      Student std4 = new Student(004, "David", 27, "English");

      std1.showInfo();
      std2.showInfo();
      std3.showInfo();
      std4.showInfo();
   }
} 

更新日期:2020 年 6 月 19 日

9K+ 瀏覽次數

開啟你的 職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.