为了理解get和set访问器,需要编写一个小程序来理解。
1.只带有get器的属性称为只读属性。无法对只读属性赋值。
只带有set器的属性称为只写属性。只写属性除作为赋值的目标外,无法对其进行引用。
同时带有get和set器的属性为读写属性。
在属性声明中,get和set器都必须在属性体的内部声明。
Program.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace fanwenqi
7 {
8
9 public class File
10 {
11 private string s_filename;
12 public string Filename
13 {
14 get { return s_filename; }
15 set {
16 if (s_filename != value)
17 s_filename = value;
18 }
19 }
20 }
21
22 class Program
23 {
24 static void Main(string[] args)
25 {
26 File f = new File();
27 f.Filename = "myfile.txt";
28 // string s = f.Filename;
29 Console.WriteLine(f.Filename);
30 }
31 }
此程序运行结果为myfile.txt。
2.通过设置断点,可以来了解get与set的具体操作过程。
运行到f.Filename = "myfile.txt"; 处进入了set的内部进行操作, myfiile.txt赋给value,然后再对value 进行判断,
把 value 赋给s_filename。
运行完set后,程序就跳到 Console.WriteLine(f.Filename);然后就进入get操作,进行取值。
所以最后运行结果是 myfile.txt。
3. 为了加深理解,又写了个相关程序
Bank.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace getset1
7 {
8 #region 工商银行
9 class GongHang
10 {
11 private int money;
12 public int Money
13 {
14 get { return money; }
15 set {
16 if (value> 0)
17 {
18 money = value;
19
20 }
21 else
22 {
23 money = 0;
24 }
25 }
26 }
27 }
28 #endregion
29 #region 兴业银行
30 class XinYe : GongHang
31 {
32 private int money;
33 public new int Money
34 {
35 get { return money; }
36 set
37 {
38 if (value> 5)
39 {
40 money = value;
41 }
42 else
43 {
44 if (value > 0 && value <= 5)
45 {
46 money = 10;
47
48 }
49 else
50 {
51 money = 0;
52 }
53 }
54 }
55
56 }
57
58 }
59 #endregion
60 class Bank
61 {
62 static void Main(string[] args)
63 {
64 GongHang g = new GongHang();
65 g.Money = 4;
66 int r1 = g.Money;
67 Console.WriteLine(r1);
68 XinYe x1 = new XinYe();
69 XinYe x2 = new XinYe();
70 x1.Money = 9;
71 x2.Money = 4;
72 int r2 = x1.Money;
73 int r3 = x2.Money;
74 Console.WriteLine(r2);
75 Console.WriteLine(r3);
76
77 }
78 }
79 }
运行结果为:4,9,10。