C# 关于属性的题

来源:百度知道 编辑:UC知道 时间:2024/05/22 17:05:02
class Test{
static void Main(){
Student stu=new student(105);
Console.WriteLine(stu.Age);
stu.Age=100;
Console.WriteLine(stu.Age);
}
}
public class Student{
private int_age=10:
public int Age{
get{
return this._age:
}
set{
if(value>0 && value<=100)
this._age=value;
}
}
}
public Student(int age){
this._age=age;
}
}
这个结果等于多少?
第一个为什么是105而不是10呢?

105
100
你如果把自己当做是计算机的话,我们可以把全部代码编号,来看看计算是如果运行这些代码的

01 class Test{
02 static void Main(){
03 Student stu=new student(105);
04 Console.WriteLine(stu.Age);
05 stu.Age=100;
06 Console.WriteLine(stu.Age);
07 }
08 }
09 public class Student{
10 private int_age=10:
11 public int Age{
12 get{
13 return this._age:
14 }
15 set{
16 if(value>0 && value<=100)
17 this._age=value;
18 }
19 }
20 }
21 public Student(int age){
22 this._age=age;
23 }
24 }

从 行03 开始,要求建立 Student 的实例,系统会对所有字段进行初始化,也就是会先运行 行10 ,这个时候 int_age 就是 10,然后运行你定义的构造方法,行22 int_age 就更新为了 105 那么在 行3 之后的属性值 Age 自然就显示为 105
你也可以试试在 22 行插入 Console.WriteLine(this.Age);
也就是将构造方法改成
public Student(int age){
Console.WriteLine(this.Age);
this._age=age;
}
你就会看见那个可爱的 10 出现在 105 之前了

105
100

Student stu=new student(105);
在这里的时候,你的类实例化的时候走的构造