VB.NET 中的多态性
在 VB.NET 中,假设我有一个函数,
Public Function Foo(ByVal currentShape as Shape)
而不是传入 Shape
对象,而是传入一个名为 Square
的 Shape
子类,如下所示:
Dim square As Square = new Square()
Foo(square)
在传入之前,我是否需要将 Square
对象转换为 Shape
对象?如果是这样,我该怎么做?
In VB.NET, say I have a function
Public Function Foo(ByVal currentShape as Shape)
Instead up passing in a Shape
object, I pass in a subclass of Shape
called Square
like such:
Dim square As Square = new Square()
Foo(square)
Do I need to convert my Square
object to a Shape
object before passing it in? If so, how do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正方形
是一个形状
。您不需要转换任何东西。
所有子类都可以隐式转换为其超类。
Square
is-aShape
.You don't need to convert anything.
All subclasses are implicitly convertible to their superclasses.
不,您不需要自己执行转换。
square
的值可以使用引用转换转换为Shape
类型的值(它仍然是一个引用)。这不会创建一个新对象 - 它只是以不同的方式查看该对象:)Foo
将只能访问声明的成员在Shape
中,尽管它们可能在Square
中被覆盖。当方法返回时,对
Foo
中的对象所做的任何更改仍然可以通过square
看到。No, you don't need to perform a conversion yourself. The value of
square
can be converted using a reference conversion to a value of typeShape
(it's still a reference). This does not create a new object - it just looks at the object in a different way :)Foo
will only be able to access members declared inShape
, although they may be overridden inSquare
.Any changes made to the object within
Foo
will still be visible viasquare
when the method returns.我很确定你可以直接传递 Square 对象。
I'm pretty sure that you can pass the Square object straight in.