程序无异常,无限循环栈溢出
报错的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//字段-》属性
namespace PropertyExample
{
class Program
{
static void Main(string[] args)
{
Student st = new Student();
//st.SetAge(20);
st.Age = 20;
Console.WriteLine(st.Age);
Student st1 = new Student();
//st1.SetAge(20);
st1.Age = 20;
Student st2 = new Student();
//st2.SetAge(20);
st2.Age = 20;
int averageAge = (st.Age + st2.Age + st1.Age) / 3;
//int averageAge1 = (st.GetAge() + st2.GetAge() + st1.GetAge()) / 3;
Console.WriteLine(averageAge);
//Console.WriteLine(averageAge1);
}
}
class Student
{
private int age;
public int Age
{
set
{
if (value >= 0 && value <= 120)
{
this.Age = value;
}
else
{
throw new Exception("Age value has error!");
}
}
get
{
return this.Age;
}
}
//public void SetAge(int value)
//{
// this.Age = value;
//}
//public int GetAge()
//{
// return this.Age;
//}
}
}
修正后代码
set
{
if (value >= 0 && value <= 120)
{
this.age = value;
}
else
{
throw new Exception("Age value has error!");
}
}
get
{
return this.age;
}
原因:
1、 private int age;该行代码被我注释掉啦,我以为不需要呐
2、使用get方法给Age属性赋值时无限递归造成栈溢出,理论上应该是给private int age赋值,而public int Age 类似构造器的功能,简化繁琐的get、set方法