How to override a getter-only property with a setter in C#?

前端 未结 3 656
闹比i
闹比i 2020-12-17 22:02

Update: This question has been revised to make it clearer. The answers below seem to reflect that this method works well. Hopefully this questio

相关标签:
3条回答
  • 2020-12-17 22:38

    Be careful with your solution as it hides the original intent for A and B. That being said, your solution does work, even when casting to base classes.

    Example:

    D d = new D();
    d.X = 2;
    B b = d as B;
    
    Assert.AreEqual(2, b.X);
    

    If the base classes can be modified, I recommend using reflection.

    0 讨论(0)
  • 2020-12-17 22:47

    UPDATE: The following is INCORRECT.

    No.

    public abstract class A
    {
        public abstract int X { get; }
    
        public int GetXPlusOne()
        {
            return X + 1;
        }
    }
    

    You won't change the value of A.X.

    var d = new D();
    d.X = 10;
    
    d.GetXPlusOne() == 1
    
    0 讨论(0)
  • 2020-12-17 22:51

    By introducing the new property XGetter in your example, you've made the solution more complex than it needs to be. You can introduce the same property and just reverse which property gets the getter and setter.

    public abstract class A
    {
        public abstract int X { get; }
    }
    public class D : A
    {
        private int _x;
        public sealed override int X { get { return XGetterSetter; } }
        public virtual int XGetterSetter { get { return this._x; } set { this._x = value; } }
    }
    

    There's just as much code in class D in the above example as there is in your original example. This just eliminates the need for class B and class C from your example.

    Semantically, this solution may not be the same. You'd have to set the XGetterSetter property as opposed to the X property. Derived classes of D would also have to override XGetterSetter as opposed to X.

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