StackOverflowException with class

后端 未结 2 1114
梦如初夏
梦如初夏 2021-01-27 03:26


I have a problem with a class that I wrote. When I try to call it I get an exception. See the code below for more clarity.
I have the class:

using Sy         


        
相关标签:
2条回答
  • 2021-01-27 03:47

    The problem is that when you try to get or set any of the properties, say, Name, there is a code path that calls the setter of the same property:

    public string Name
    {
        get { return this.Name; } // <<<<====== HERE
        private set
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new NoNullAllowedException("Name is mandatory");
            }
            else
            {
                this.Name = value; // <<<<==== HERE
            }
        }
    }
    

    this.Name means "call getter/setter of Name with the value of value". This creates infinite recursion, causing stack overflow.

    To implement properties with conditions like that you need to define fields that store the actual data. A common approach is to make these fields private, and name them with the same name as the property, except the first letter should not be capitalized:

    private string name; // <<<<==== Add this
    public string Name
    {
        get { return name; } // <<<<====== change
        private set
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new NoNullAllowedException("Name is mandatory");
            }
            else
            {
                name = value; // <<<<==== change
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-27 03:48

    change

    get { return this.Name; }
    

    to

    get;
    

    the same goes for the Age property.

    This is because this.Name is using the get method you are overriding, thus creating the glorious StackOverflowException! If you need a field for name and age you have to create one yourself like:

    private string name;
    public string Name
    {
        get { return this.name; }
        private set
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new NoNullAllowedException("Name is mandatory");
            }
            else
            {
                this.name = value;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题