“父”对象的实例如何使用其子对象的方法/属性?

时间:2017-12-19 21:46:06

标签: .net vb.net

似乎“父”对象维护已设置为的子对象的“详细信息”。虽然这是我实际想要发生的事情 - 我不明白为什么这种情况正在发生,这让我很害怕。

我希望当新的父对象设置为子对象时,不在父对象中的任何属性/方法都将丢失/不可访问。但似乎如果我将其设置如下,情况并非如此。有人可以解释为什么会发生这种情况,如果这样适合以这种方式使用?

(为一个可怕的例子道歉)

考虑以下三个类:

Public Class Person

    Public Property FirstName As String
    Public Property LastName As String

    Public Overridable Function WriteStatement() As String
        Return "[Unknown] " & FirstName & " " & LastName
    End Function

End Class

Public Class Man

    Inherits Person
    Public Property gender As String = "Male"

    Public Overrides Function WriteStatement() As String
        Return "[" & gender & "] " & FirstName & " " & LastName
    End Function

End Class

Public Class Woman

    Inherits Person
    Public Property gender As String = "Female"

    Public Overrides Function WriteStatement() As String
        Return "[" & gender & "] " & FirstName & " " & LastName
    End Function


End Class

然后执行代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Dim boy As New Man
Dim girl As New Woman

boy.FirstName = "Scott" : boy.LastName = "Smith"

girl.FirstName = "Jane"
girl.LastName = "Jones"

Dim people As New List(Of Person)
Dim malePerson As New Person
Dim femalePerson As New Person

malePerson = boy
femalePerson = girl

people.Add(malePerson)
people.Add(femalePerson)

For Each p As Person In people
    MsgBox(p.WriteStatement())
Next

'Outputs:
' [Male] Scott Smith
' [Female] Jane Jones
'
'Expected:
' [Unknown] Scott Smith
' [Unknown] Jane Jones

End Sub

2 个答案:

答案 0 :(得分:1)

在这种情况下,术语“父母”和“儿童”不合适。你所说的是基类型和派生类型。当你谈到将对象设置为对象时,你也错了。这只是荒谬的。一个对象就是它。您可以将变量设置为对象,但不会更改对象的内容。 OOP旨在模仿现实生活。如果你把一个男人或一个女人放在一个人的预期之中,他们会不再是一个男人或一个女人?不,他们没有,编程对象是相同的。如果类型重写成员,则在该类型的对象上调用该成员将调用该派生实现,无论引用的类型是派生类型还是基类型。这就是压倒一切的作用。

答案 1 :(得分:0)

您应该在父类中使用它:

public MUSTOVERRIDE class person
Public mustoverride Property gender As String

并在子类中:

Public overrides Property gender As String = "Male"