首页 > 解决方案 > 使用属性和继承的构造函数时出现意外的 StackOverflow 异常

问题描述

在 C# 中使用继承和属性(出于教学原因)玩弄一个奇怪的异常。对于专家来说应该是小菜一碟,但仍然让我感到困惑。这是我的代码:

public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }
public class Employee : Person
    {
        public int ID
        {
            get
            {
                return ID;
            }
            set
            {
                if (ID < 0 || ID > 999)
                    throw new Exception("Id must between [000-999]");
                ID = value;
            }
        }

        public Employee(string name, int age, int id):base(name, age)
        {
            ID = id;
        }
    }

static void Main(string[] args)
        {
            var per = new Person("John", 32);
            var imp = new Employee("Michael", 44, 330);
         }

执行我得到了一个 StackOverflow。最后一个 StackTrace 指向 Employee 类中 Employee.get_ID () 行的错误。

提前感谢您的任何帮助!

标签: c#constructorproperties

解决方案


好吧,财产会自己ID回来

    public int ID
    {
        get
        {
            return ID;
        }
    ...

因此你有堆栈溢出:当你读取ID它时调用ID它反过来调用ID等。同样的问题set:你为属性ID赋值,导致赋值给ID等。为了打破这个恶性循环,让我们引入一个支持字段

    private int m_ID;

    public int ID
    {
        get
        {
            //DONE: now we just read m_ID, not call the property
            return m_ID;
        }
        set
        {
            //DONE: you want to validate value, not ID, right?
            //DONE: ArgumentOutOfRangeException - value is out of valid range 
            if (value < 0 || value > 999)
                throw new ArgumentOutOfRangeException(nameof(value),
                                                     "Id must between [000-999]");

            //DONE: we assign value to the field, not to the property
            m_ID = value;
        }
    }

推荐阅读