Calling base class property from object of derived class without marking it virtual
How to call x of class a from object of class b without marking x of class a as virtual. Is it possible
public class a { public int x { get; set; } }
public class b : a { public int x { get; set; } }
public class c {
a _a = new a();
b _b = new开发者_StackOverflow中文版 b();
public c()
{
int y=_a.x;
y=_b.x;
_b.x = y;
}
}
base.x()
should work inside the b
type (but that isn't what you have here).
In the "method hiding" scenario (what you have), it also largely depends on what a variable is typed as, so casting to a
should work:
a tmp = _b;
tmp.x = ... // talks to a.x, not b.x
or more succinctly:
((a)_b).x = ... // talks to a.x, not b.x
Use typecast:
public class c
{
a _a = new a();
b _b = new b();
void Test() {
int y = _b.x; // This is "x" of "b"
a _b_as_a = (a)_b;
int z = _b_as_a.x; // This is "x" of "a" of "b"
}
}
Besides typecasting (as above, although that won't work if you don't know its parent's type) you can't, so I would advise re-structuring one of those classes. You should probably make x virtual, or change the property x inside class b to something different, or call base.x inside b's x implementation.
精彩评论