Override abstract readonly property to read/write property

前端 未结 5 1317
死守一世寂寞
死守一世寂寞 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:29

    Would this suit your needs?

    public abstract class TheBase
    {
        public int Value
        {
            get;
            protected set;
        }
    }
    public class TheDerived : TheBase
    {
        public new int Value
        {
            get { return base.Value; }
            set { base.Value = value; }
        }
    }
    

    The virtual was removed, but the base value is still the only storage for the value. So this should show '5'. And the compiler should fuss about b.Value = 4;

    TheDerived d = new TheDerived();
    d.Value = 5;
    TheBase b = d;
    //b.Value = 4;    // uncomment for compiler error
    cout << "b.Value == " << b.Value << endl;
    

    -Jesse

提交回复
热议问题