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

前端 未结 2 1584
不思量自难忘°
不思量自难忘° 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: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;  }
      }
    }
    

提交回复
热议问题