Override get, But not set

前端 未结 13 2471
暖寄归人
暖寄归人 2020-12-14 14:17

I have an abstract class that defines a get, but not set, because as far as that abstract class is concerned, it needs only a get.

13条回答
  •  孤城傲影
    2020-12-14 14:45

    Siege

    abstract class TestBase
    {
        public abstract int Int { get; }
    }
    
    class TestDerivedHelper : TestBase
    {
        private int _Int;
        public override int Int
        {
            get
            {
                return _Int;
            }
        }
    
        protected void SetInt(int value)
        {
            this._Int = value;
        }
    }
    
    class TestDerived : TestDerivedHelper
    {
        public new int Int
        {
            get { return base.Int; }
            set { base.SetInt(value); }
        }
    }
    

    Using TestDerived will have the functionality you're looking for. The only drawback I can see from this method is that you have to implement every abstract method in TestDerivedHelper, but it gives you more control later.

    I use this approach and works very well for me. Also, I made my "TestDerivedHelper" class abstract too, then all the methods must be implemented on "TestDerived" class.

提交回复
热议问题