Adding a set accessor to a property in a class that derives from an abstract class with only a get accessor

后端 未结 3 573
一整个雨季
一整个雨季 2021-01-07 22:47

I have an abstract class, AbsClass that implements an interface, IClass. IClass has a couple properties with only Get acce

3条回答
  •  礼貌的吻别
    2021-01-07 23:11

    This works the way it does because properties aren't truly virtual - their accessor methods are. Thus, you cannot override set if there wasn't one in the base class.

    What you can do is override and shadow the base class implementation, and provide your own new read/write properties. I don't know of any way to do this without introducing an additional class in the hierarchy:

    class AbsClassB : AbsClass
    {
        public override double Top { get { return ((ConcClassB)this).Top } }
        public override double Bottom { get { return ((ConcClassB)this).Bottom } }
    }
    
    
    class ConcClassB :  AbsClassB
    {
        new public double Top
        {
            get { ... }
            set { ... }
        }
    
        new public double Bottom
        {
            get { ... }
            set { ... }
        }
    }
    

    A better idea would be to define a protected virtual method right in AbsClass, and implement Top.get and Bottom.get in terms of that method. Then you can override that method directly in ConcClassB, and shadow the properties, without the need for an extra class:

    abstract class AbsClass : IClass
    {
        public double Top
        {
            get { return GetTop(); }
        }
    
        public double Bottom
        {
            get { return GetBottom(); }
        }
    
        protected abstract double GetTop();
    
        protected abstract double GetBottom();
    }
    
    class ConcClassB :  AbsClass
    {
        new public double Top
        {
            get { ... }
            set { ... }
        }
    
        new public double Bottom
        {
            get { ... }
            set { ... }
        }
    
        protected override double GetTop()
        {
            return Top;
        }
    
        protected override double GetBottom()
        {
            return Bottom;
        }
    }
    

提交回复
热议问题