2008/12/06(Sat) 11:40:45 編集(投稿者)
> また、もっとスマートな方法はないのでしょうか
スマートかどうかはわかりませんが、TestNodeとTestNode専用のコレクションを用意する方法にすると
TreeNodeとほぼ同じような使い方をすることができますので、使う人は使いやすいかもしれませんね。
私が書くなら・・・というサンプルです。(あくまでサンプルなので鵜呑みにしないでね)
※以下のコードは、Parentの制御は手抜きをしてAdd/Insert/Remove/RemoveAtしかやってません。
Imports System.Collections
Imports System.Collections.Generic
Public Class TestNode
Private _parent As TestNode
Private _nodes As TestNodeCollection
Public Sub New()
_nodes = New TestNodeCollection(Me)
End Sub
Public ReadOnly Property Nodes() As TestNodeCollection
Get
Return _nodes
End Get
End Property
Public Property Parent() As TestNode
Get
Return _parent
End Get
Friend Set(ByVal value As TestNode)
_parent = value
End Set
End Property
End Class
Public Class TestNodeCollection
Implements IList(Of TestNode)
Private _nodes As List(Of TestNode)
Private _parent As TestNode
Public Sub New(ByVal parent As TestNode)
_parent = parent
_nodes = New List(Of TestNode)
End Sub
Public Sub Add(ByVal item As TestNode) Implements ICollection(Of TestNode).Add
item.Parent = _parent
_nodes.Add(item)
End Sub
Public Sub Clear() Implements ICollection(Of TestNode).Clear
_nodes.Clear()
End Sub
Public Function Contains(ByVal item As TestNode) As Boolean _
Implements ICollection(Of TestNode).Contains
_nodes.Contains(item)
End Function
Public Sub CopyTo(ByVal array() As TestNode, ByVal arrayIndex As Integer) _
Implements ICollection(Of TestNode).CopyTo
_nodes.CopyTo(array, arrayIndex)
End Sub
Public ReadOnly Property Count() As Integer Implements ICollection(Of TestNode).Count
Get
Return _nodes.Count
End Get
End Property
Public ReadOnly Property IsReadOnly() As Boolean _
Implements ICollection(Of TestNode).IsReadOnly
Get
Return False
End Get
End Property
Public Function Remove(ByVal item As TestNode) As Boolean _
Implements ICollection(Of TestNode).Remove
item.Parent = Nothing
Return _nodes.Remove(item)
End Function
Public Function GetEnumerator() As IEnumerator(Of TestNode) _
Implements IEnumerable(Of TestNode).GetEnumerator
Return _nodes.GetEnumerator()
End Function
Public Function IndexOf(ByVal item As TestNode) As Integer Implements IList(Of TestNode).IndexOf
Return _nodes.IndexOf(item)
End Function
Public Sub Insert(ByVal index As Integer, ByVal item As TestNode) Implements IList(Of TestNode).Insert
item.Parent = _parent
_nodes.Insert(index, item)
End Sub
Default Public Property Item(ByVal index As Integer) As TestNode Implements IList(Of TestNode).Item
Get
Return _nodes.Item(index)
End Get
Set(ByVal value As TestNode)
value.Parent = _parent
_nodes.Item(index) = value
End Set
End Property
Public Sub RemoveAt(ByVal index As Integer) Implements IList(Of TestNode).RemoveAt
_nodes(index).Parent = Nothing
_nodes.RemoveAt(index)
End Sub
Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Return _nodes.GetEnumerator()
End Function
End Class