Given that code:
class B
{
public virtual string Method()
{
return "base";
}
}
class D : B
{
public override string Method()
{
return "derived";
}
}
D d = new D();
B b = d as B;
b.Method();
"derived" is the output.
But why exactly? I mean, b is a new object of type B, isnt it? Or is it the same object (in memory) as d? If so, what's the runtime type of b then, B or D?
Thanks
The rule is simple: b
is a reference to an object of type D
. You could say that the run-time type of b
is D
but that's not particularly helpful terminology.
You can do
B b = new D();
b.Method();
and you'd still get "derived". As @Bathsheba mentioned, what matters is the object type not the reference.
Imagine the typical OOP example where you have a base class Shape
with derived classes Circle
, Square
, etc. with a virtual method Area
.. if you have a method like this:
void ShowArea(Shape shape)
{
Console.WriteLine(shape.Area());
}
The fact that the reference doesn't matter (but rather the actual object type) enables a method like the above to accept any type of Shape
and still print the correct area
b is a new object of type B, isnt it?
No, b
is an existing object of type B
, which points to the same object you created just above it: d
. The only difference is that you have cast the object as its parent type -- B
, so b
is treated as a B
rather than the more-derived type D
.
The reason you get the output "derived" is because the method is overridden in the derived class and that's how overriding works. Just because you declare a variable (ie b
) as its less-derived type B
doesn't mean it isn't still actually the more-derived type D
. That's the nature of polymorphism.
B b = d as B;
我相信这行代码仅将d转换为B类的类型,但该值仍保持为“派生”。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.