简体   繁体   English

VB.NET中的多态

[英]Polymorphism in VB.NET

In VB.NET, say I have a function 在VB.NET中,说我有一个功能

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: 而不是向上传递Shape对象,而是传递Shape名为Square的子类,如下所示:

Dim square As Square = new Square()
Foo(square)

Do I need to convert my Square object to a Shape object before passing it in? 在传递该对象之前,是否需要将其Square对象转换为Shape对象? If so, how do I do this? 如果是这样,我该怎么做?

Square is-a Shape . Square 是一个 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). 可以使用引用转换square的值转换Shape类型的值(它仍然是引用)。 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 . 创建一个新的对象-它只是着眼于以不同的方式对象:) Foo将只能访问声明成员Shape ,尽管它们可以被覆盖 Square

Any changes made to the object within Foo will still be visible via square when the method returns. 当方法返回时,在Foo对对象所做的任何更改仍将通过square显示。

我很确定您可以直接传递Square对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM