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

后端 未结 3 574
一整个雨季
一整个雨季 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:04

    I am kind of curious as to why you would want these implementation classes to have public setter methods that are not part of the public interface. It sounds to me like you may actually want these to be more restricted than public?

    Other than that, I'm having a hard time thinking of a problem with this approach. They would "hide" any properties from the superclass, but there are no property setters in the superclass anyway, so that seems ok. It seems like it may be the simplest workaround.

    0 讨论(0)
  • 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;
        }
    }
    
    0 讨论(0)
  • 2021-01-07 23:20

    Use a global variable.

    0 讨论(0)
提交回复
热议问题