让我说我上课了。 (这个例子会有点愚蠢和低效,但只是为了说明一点)
Public class Node
Private children as new list(of Node)
Public Sub removeChild(n as Node)
children.remove(n)
End Sub
End Class
然后我继承了那个类并做了一些补充
Public class BookNode
Inherits Node
Public title as string
Public sub removeChildByTitle(t as string)
For i = 0 to children.count-1
if (children(i).title = t) then removeChild(children(i))
Next
End Sub
End class
但这是我们遇到问题的地方。 children(i)是一种Node,并没有名为title的变量。我可以将引用转换为BookNode来进行比较,或者我可以将子句声明为(对象的)列表。但是前者很笨拙并且使得它更难以阅读,而后者在计算上效率低下。
有没有办法让处理自己的类的方法和变量自动重新编写成继承它们的类?
答案 0 :(得分:1)
首先,children
无法访问BookNode
,因为它Private
。你需要把它Protected
:
Public class Node
Protected children as new list(of Node)
Public Sub removeChild(n as Node)
children.remove(n)
End Sub
End Class
另外,做你需要的正确方法是做你建议的事情,即将每个人投射到ChildNode
实例进行比较:
Public class BookNode
Inherits Node
Public title as string
Public sub removeChildByTitle(t as string)
For i = 0 to children.count-1
if (DirectCast(children(i), ChildNode).title = t) then removeChild(children(i))
Next
End Sub
End class
最后,我建议您使用属性而不是children
的字段。我有很多理由这样做,我不打算在这里阐述。所以:
Public class Node
Protected Property Children as list(of Node)
Public Sub New()
Children = New List(Of Node)
End Sub
Public Sub removeChild(n as Node)
children.remove(n)
End Sub
End Class