C# How to add a property setter in derived class?

前端 未结 2 1558
不思量自难忘°
不思量自难忘° 2021-01-07 23:37

I have a requirement where I have a number of classes all derived from a single base class. The base class contains lists of child classes also derived from the same base c

相关标签:
2条回答
  • 2021-01-08 00:00

    You can use the 'new' keyword but this will replace property, what you want is not possible with override.

    public class BaseClass
    {
        private BaseClass _Parent;
        public virtual decimal Result
        {
            get { return ((_Parent != null) ? _Parent.Result : -1); }
        }
    }
    
    public class DerivedClass : BaseClass
    {
        private decimal _Result;
        public new decimal Result
        {
            get { return _Result; }
            set { _Result = value;  }
        }
    }
    
    0 讨论(0)
  • 2021-01-08 00:03

    I ended up changing the way I handled it and leaving the set in the base class however rather than having the base class getter / setter do nothing I threw a NotImplemented / NotSupported exception.

    public class BaseClass
    {
      private BaseClass _Parent;
      public virtual decimal Result
      {
         get
         {
          if (Parent == null)
            throw new NotImplementedException("Result property not valid");
    
          return Parent.Result;
        }
        set
        {
          throw new NotSupportedException("Result property cannot be set here");
        }
      }
    }
    
    public class DerivedClass : BaseClass
    {
      private decimal _Result;
      public override decimal Result
      {
        get { return _Result; }
        set { _Result = value;  }
      }
    }
    
    0 讨论(0)
提交回复
热议问题