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?
Square
is-a Shape
.
You don't need to convert anything.
All subclasses are implicitly convertible to their superclasses.
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 type Shape
(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 in Shape
, although they may be overridden in Square
.
Any changes made to the object within Foo
will still be visible via square
when the method returns.
我很确定您可以直接传递Square对象。
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.