C# 中的“this”關鍵詞
C# 中的“this”關鍵詞用於引用類當前的例項。如果方法引數和類欄位具有相同名稱,則還可以使用它來區分這兩個引數和欄位。
“this”關鍵詞的另一種用法是呼叫同一類中建構函式中的另一個建構函式。
在此,例如,我們顯示了一個包含學生記錄(即 ID、姓名、年齡和科目)的記錄。為了引用當前類的欄位,我們在 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(); } }
廣告