StackOverflowException with class

后端 未结 2 1145
梦如初夏
梦如初夏 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
            }
        }
    }
    

提交回复
热议问题