StackOverflowException with class

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

提交回复
热议问题