VB.net 中的重载与覆盖 [英] Overloads Versus Overrides in VB.net
问题描述
Other1
和 Other2
类的 Previous
属性有什么行为差异.
What are the behavior differences for the Previous
Property of Other1
and Other2
Class.
注意Other2
的重载Previous
属性的返回类型已更改为Other2
,而它保持为Base
用于 Other1
.
Note than the return type of the overloaded Previous
Property of Other2
has been changed to Other2
while it stays as Base
for Other1
.
Public Class Base
Private _Previous as Base
Protected Overridable ReadOnly Property Previous As Base
Get
Return _Previous
End Get
End Property
Public Sub New(Previous as Base)
_Previous = Previous
End Sub
End Class
Public Class Other1
Inherits Base
Private _Parent as SomeType
Protected Overrides ReadOnly Property Previous As Base
Get
Return _Parent.Previous.Something
End Get
End Property
Public Sub New(Parent as SomeType)
MyBase.New(Nothing)
_Parent = Parent
End Sub
End Class
Public Class Other2
Inherits Base
Private _Parent as SomeType
Protected Overloads ReadOnly Property Previous As Other2
Get
Return _Parent.Previous.Something
End Get
End Property
Public Sub New(Parent as SomeType)
MyBase.New(Nothing)
_Parent = Parent
End Sub
End Class
推荐答案
在我对 Jim Wooley 的回答,它看起来像是对重载的属性造成了阴影."我在这篇文章中看到了曙光.
After one of my comment to Jim Wooley's answer, "it look like it Shadows the overloaded property." I saw the light in this article.
因此,Other2 类中的重载更像是遮蔽而不是覆盖.文章中有一个评论特别有启发性:
So, the Overloads in the Other2 class act some more like shadowing than override. There is one of the comments in the article that is particularly instructive :
之所以会产生混淆,是因为关键字重载"并不是 C# 程序员认为的传统 OO 意义上的重载.这是一种特定于 VB.Net 的隐藏类型.在大多数情况下,您实际上可以将关键字 SHADOWS 与 OVERLOADS 交换,并且行为是相同的.不同之处在于当您有一个带有多个重载方法签名的基类时.如果您在子类中声明一个具有匹配名称和 SHADOWS 关键字的方法,它将隐藏基类中该方法的每个重载.如果您改用 OVERLOADS 关键字,它只会隐藏具有相同签名的基类方法.
The confusion arises because the keyword "Overloads" isn't what a C# programmer considers an overload in the traditional OO sense. It's a type of hiding that is specific to VB.Net. You can actually swap the keyword SHADOWS with OVERLOADS in most cases, and the behavior is the same. The difference is when you have a base class with multiple overloaded method signatures. If you declare a method in a subclass with a matching name, and the SHADOWS keyword, it will hide EVERY overload of that method in the base class. If you use the OVERLOADS keyword instead, it will only hide the base class method with an identical signature.
这篇关于VB.net 中的重载与覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!