导致stackoverflow异常的递归属性

时间:2017-02-13 19:32:44

标签: c# recursion

我们刚接触到我的C#类中的属性,当我尝试按照我的老师告诉我们的方式创建属性时,我最终得到一个抛出stackoverflow异常的递归调用 - 特别是对于我的属性限制“设置”部分。在此先感谢,希望你能帮忙:)!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Propertiesøvelse
{
    class Person
    {
        public Person(string name, string ssNumber)
        {
            Name_ = name;
            SSNumber_ = ssNumber;
            Height_ = 0;
            Weight_ = 0;
        }


        public string Name_ { get; set; }
        public string SSNumber_ { get; set; }

        public int Height_
        {
            get
            {
                return Height_;
            }
            set
            {
                if (value >= 40 && value <= 250)
                    Height_ = value;
                else
                {
                    Height_ = 0;
                }
            }
        }

        public double Weight_
        {
            get
            {
                return Weight_;

            }

            set
            {
                if (value >= 4.0 && value <= 200.0)
                    Weight_ = value;

            }

        }

        public override string ToString()
        {
            return

                Convert.ToString(Name_ + Environment.NewLine + SSNumber_ + Environment.NewLine + Height_ +
                                 Environment.NewLine + Weight_ + Environment.NewLine);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Propertiesøvelse
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person("Anders", "1234567890");

            p.Height_ = 185;
            p.Weight_ = 78.4;

            int height = p.Height_;
            double weight = p.Weight_;

            Console.WriteLine(p.ToString());
        }
    }
}

0 个答案:

没有答案