[英]Type of object after as cast?
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?
我的意思是,b是类型B的新对象,不是吗? Or is it the same object (in memory) as d?
还是它与d是同一对象(在内存中)? If so, what's the runtime type of b then, B or D?
如果是这样,那么b或B的运行时类型是什么?
Thanks 谢谢
The rule is simple: b
is a reference to an object of type D
. 规则很简单:
b
是对类型D
的对象的引用。 You could say that the run-time type of b
is D
but that's not particularly helpful terminology. 您可以说
b
的运行时类型为D
但这并不是特别有用的术语。
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.
正如@Bathsheba提到的,重要的是对象类型而不是引用。
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: 想象一下一个典型的OOP示例,其中有一个基类
Shape
,而派生类Circle
, Square
等具有虚拟方法Area
..如果您有如下方法:
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 引用无关紧要(而是实际的对象类型)这一事实使上述方法可以接受任何类型的
Shape
并仍然打印正确的区域
b is a new object of type B, isnt it?
b是类型B的新对象,不是吗?
No, b
is an existing object of type B
, which points to the same object you created just above it: d
. 不,
b
是类型B
的现有对象,它指向您在其上方创建的同一对象: 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
. 唯一的区别是,已将对象强制转换为其父类型
B
,因此b
被视为B
而不是派生自更广泛的类型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
. 仅仅因为您将变量(即
b
)声明为派生类型较低的类型B
并不意味着它实际上仍不是派生类型较高的类型D
That's the nature of polymorphism. 这就是多态性的本质。
B b = d as B;
我相信这行代码仅将d转换为B类的类型,但该值仍保持为“派生”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.