How to increase the access modifier of a property

前端 未结 3 1950
面向向阳花
面向向阳花 2021-01-04 18:17

I\'m trying to create a set of classes where a common ancestor is responsible for all the logic involved in setting various properties, and the descendants just change the a

3条回答
  •  感动是毒
    2021-01-04 19:12

    You can't change the access, but you can re-declare the member with greater access:

    public new int PropertyOne
    {
        get { return base.PropertyOne; }
        set { base.PropertyOne = value; }
    }
    

    The problem is that this is a different PropertyOne, and inheritance / virtual might not work as expected. In the above case (where we just call base.*, and the new method isn't virtual) that is probably fine. If you need real polymorphism above this, then you can't do it (AFAIK) without introducing an intermediate class (since you can't new and override the same member in the same type):

    public abstract class ChildOneAnnoying : Parent {
        protected virtual int PropertyOneImpl {
            get { return base.PropertyOne; }
            set { base.PropertyOne = value; }
        }
        protected override int PropertyOne {
            get { return PropertyOneImpl; }
            set { PropertyOneImpl = value; }
        }
    }
    public class ChildOne : ChildOneAnnoying {
        public new int PropertyOne {
            get { return PropertyOneImpl; }
            set { PropertyOneImpl = value; }
        }
    }
    

    The important point in the above is that there is still a single virtual member to override: PropertyOneImpl.

提交回复
热议问题