C#簡單介紹在區域中運用this.變數指向property變數
在練習中,當運用建構子傳遞參數,建構子constructor需要創建接收參數的變數時,若遇到變數名稱與property相同時,我們可以利用this來讓電腦區別誰是property的變數,誰是建構子的區域變數。
例如:
public int id, grade, height; //property
public string name; //property
public student(string name,int id,int grade,int height) //建構子(constructor)
{
this.name = name;
this.id = id;
this.grade = grade;
this.height = height;
}
運用this可以將相同名稱的變數指向property,而另一個相同名稱則是區域變數。
主程式:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
student a = new student("Wes Wang",1234567,3,176);
MessageBox.Show(a.introduce(),"基本資料");
}
}
物件程式碼:
class student
{
//property
public int id, grade, height;
public string name;
public student(string name,int id,int grade,int height)
{
this.name = name;
this.id = id;
this.grade = grade;
this.height = height;
}
//method
public string introduce()
{
return "名字:" + name + "\r\n號碼:" + id + "\r\n年級:" + grade + "\r\n身高:" + height;
}
}
留言
張貼留言