C# - Get and Set 存取器

語法

……… // 宣告變數(通常是 public)
{ get { …. } // 希望變數讀取時執行的程式碼
set { …. } // 希望數值存入時執行的程式碼
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class User
{
private string Username;
private string Password;
private int hp;
public int HP
{
get { return hp; }//在讀取 HP 時會自動呼叫
set { if (value < 0) {//在存入數值時自動呼叫
hp = 0;
} else {
hp = value;
} }
}

public void hurt(int decreaseHP)
{
if (hp >= decreaseHP)
{
hp -= decreaseHP;
}
else
{
hp = 0;
}
}
public int getHP()
{
return hp;
}

public User(string Username, string Password)
{
this.Username = Username;
this.Password = Password;
this.hp = 30;
}





}
1
2
3
4
private void button1_Click(object sender, EventArgs e)
{
User user = new User("Tum","1234");
MessageBox.Show(""+user.HP); }

如果只留下 get 存取器,該變數就會變成「唯讀」

Get & Set 存取器可以用來即時運算一些平常大家認為是變數的數值,像是 Money

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class User
{

private int count1, count5, count10;
public int Money
{
get { return count1 + count5 * 5 + count10 * 10; }
}


public User(string Username, string Password)
{
this.Username = Username;
this.Password = Password;
this.hp = 30;
this.count1 = 1;
this.count5 = 1;
this.count10 = 1;

}


}
1
2
3
4
5
private void button1_Click(object sender, EventArgs e)
{
User user = new User("Tum","1234");

MessageBox.Show(""+user.Money); }

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2020 CYC'S BLOG All Rights Reserved.

UV : | PV :