Stack overflow exception thrown from overridden property from abstract base class

后端 未结 3 1882
深忆病人
深忆病人 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:43

    The abstract property declaration in the base class just states: "derived classes MUST implement a property called Status, with a getter and setter". In your derived class, calling this.Status inside your getter is illegal (causes the stack overflow).

    To fix this, use a property with a backing field in your derived class:

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

提交回复
热议问题