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

家住魔仙堡 提交于 2019-11-30 19:45:48

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!