Stack overflow exception thrown from overridden property from abstract base class

后端 未结 3 1883
深忆病人
深忆病人 2021-01-28 14:09

I have a base class with the following (trimmed for brevity) declaration:

public abstract class MyBaseClass
{    
  public int RecordId { get; private set; }
  p         


        
3条回答
  •  难免孤独
    2021-01-28 14:27

    The setter in MySpecificClass shouldn't be a problem, but the getter definitely is - internally, a call to an instance of MySpecificClass's Status will be making a call to itself to see which value to return which will make a call to itself to see... well. You get the idea.

    I'd use a protected class variable rather than an auto-property.

    public abstract class MyBaseClass
    {
        protected string _status;
        public virtual string Status
        {
            get { return _status; }
            set { _status = value; } 
        }
    }
    
    public class MySpecificClass : MyBaseClass
    {
        public override string Status
        {
            get
            {
                if(_status == "something")
                    return "some status";
                else
                    return "some other status";
            }
            set
            {
                _status = value;
            }
        }
    }
    

提交回复
热议问题