Override abstract readonly property to read/write property

前端 未结 5 1308
死守一世寂寞
死守一世寂寞 2020-12-10 11:14

I would like to only force the implementation of a C# getter on a given property from a base abstract class. Derived classes might, if they want, also provide a setter for t

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 11:38

    You can't do it directly, since you can't new and override with the same signature on the same type; there are two options - if you control the base class, add a second property:

    public abstract class Base
    {
        public int Property { get { return PropertyImpl; } }
        protected abstract int PropertyImpl {get;}
    }
    public class Derived : Base
    {
        public new int Property {get;set;}
        protected override int PropertyImpl
        {
            get { return Property; }
        }
    }
    

    Else you can introduce an extra level in the class hierarchy:

    public abstract class Base
    {
        public abstract int Property { get; }
    }
    public abstract class SecondBase : Base
    {
        public sealed override int Property
        {
            get { return PropertyImpl; }
        }
        protected abstract int PropertyImpl { get; }
    }
    public class Derived : SecondBase
    {
        public new int Property { get; set; }
    
        protected override int PropertyImpl
        {
            get { return Property; }
        }
    }
    

提交回复
热议问题