如何覆盖在C#中的setter仅吸气属性? [英] How to override a getter-only property with a setter in C#?
问题描述
今天遇到了一个问题,我需要重写基类的唯一吸气属性同时具有getter和setter。目前的共识似乎是,这是不可能的,但我认为我找到了一个方法。
Ran into a problem today where I needed to override a base class's getter-only property with both a getter and setter. Current consensus seems to be that this is impossible, but I think that I found a method.
public abstract class A
{
public abstract int X { get; }
}
public class B : A
{
public override int X { get { return 0; } }
}
/*public class C : B //won't compile: can't override with setter
{
private int _x;
public override int X { get { return _x; } set { _x = value; } }
}*/
public abstract class C : B //abstract intermediate layer
{
public sealed override int X { get { return this.XGetter; } }
protected abstract int XGetter { get; }
}
public class D : C //does same thing, but will compile
{
private int _x;
protected sealed override int XGetter { get { return this.X; } }
public new virtual int X { get { return this._x; } set { this._x = value; } }
}
我觉得 D
现在相当于一个类从 B继承
,同时还能够在二传手覆盖。这是正确的?
I think that D
is now equivalent to a class inheriting from B
while also being able to override in a setter. Is this correct?
推荐答案
小心你的解决方案,因为它隐藏了A和B的初衷话虽这么说,你的。解决方案不工作,甚至转换为基类时
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.
例如:
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.
这篇关于如何覆盖在C#中的setter仅吸气属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!