如下代码:
1 public class Age 2 { 3 4 private int ageNum ; 5 6 public int AgeNum { 7 get{ 8 return this.ageNum; 9 } 10 11 set{ 12 this.ageNum = value; 13 } 14 } 15 16 public int getAgeNum(){ 17 return ageNum; 18 } 19 20 public void setAgeNum(int age){ 21 this.ageNum = age; 22 } 23 24 }
在Main中做如下操作:
1 Age age = new Age (); 2 age.setAgeNum (234); 3 Console.WriteLine ("age=" + age.AgeNum); 4 5 age.AgeNum = 122; 6 Console.WriteLine ("age=" + age.getAgeNum());
输出:
age=234
age=122
但如果将 set get 采用简写方式,代码如下
public class Age { private int ageNum ; public int AgeNum { set; get; } public int getAgeNum(){ return ageNum; } public void setAgeNum(int age){ this.ageNum = age; } }
Main中内容不变,得到如下结果
age=0
age=234
如果修改Main中代码顺序如下
1 age.AgeNum = 122; 2 Console.WriteLine ("age=" + age.getAgeNum()); 3 4 age.setAgeNum (234); 5 Console.WriteLine ("age=" + age.AgeNum);
结果为
age=0
age=122
时间: 2024-12-29 10:36:42