我有一个基类和一个子类,它们都有相同的属性,我不明白为什么 VB 要我对子类中的属性使用“重载”。不同之处在于属性的子类版本是 Shared
而父类基本上是用于结构的。属性如下所示:
Public MustInherit Class Parent
Public ReadOnly Property Species As String
Get
Return "Should get species from a child."
End Get
End Property
End Class
Public Class Child
Inherits Parent
Public Shared ReadOnly Property Species As String
Get
Return "Species1"
End Get
End Property
End Class
Species
在带有警告消息的子类中的 Public Shared ReadOnly Property Species As String
行中被标记
property 'Species' shadows an overloadable member declared in the base class 'Parent'. If you want to overload the base method, this method must be declared 'Overloads'.
我想知道的是为什么它想让这个重载?当不同的参数被传递给具有详细记录的同名函数时,通常会使用重载,但我没有发现任何东西可以解释为什么在这种情况下突然建议重载。
注意:代码正确地报告了“Species1”,无论是否有“过载”或没有增加我对它实际作用的困惑...
最佳答案
If you want to overload the base method, this method must be declared 'Overloads'.
错误消息过于笼统。注意它是如何谈论一个方法的,即使警告是关于一个属性的。您不能重载属性。
如果我是法国国王,我会把错误信息写成这样:
Property 'Species' hides the 'Species' property inherited from the 'Parent' base class. Use the Shadows keyword to suppress this warning if hiding was intended. Change the name of the property if hiding was not intended.
这个警告几乎不应该被忽略,因为它几乎总是标识代码味道。为 Child.Species 使用 Shared 关键字非常奇怪,几乎可以肯定不是您想要的。任何通过 Parent 类型的引用使用您的 Child 对象的代码总是会得到错误的物种名称,因为它将使用 base 属性。此处更明智的做法是声明 Parent.Species 属性 Overridable 并在 Child.Species 属性声明中使用 Overrides 关键字,而不使用 Shared。
关于vb.net - "Overloads"在子类中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17452769/