Process is terminated due to StackOverflowException.

程序无异常,无限循环栈溢出

报错的代码

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方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值