2013-03-08 82 views
0

在下面的例子中,我想將.sort()方法隱藏到客戶端,我怎麼能實現這一點?隱藏VB.NET中的一個集合

Namespace test 
    Class Figure 
    Implements IComparable(Of Figure) 
    Public Property Area As Double 
    Public Function CompareTo(ByVal other As Figure) As Integer Implements System.IComparable(Of Figure).CompareTo 
     CompareTo = Me.Area.CompareTo(other.Area) 
    End Function 
    End Class 
    Class Figures 
    Inherits System.Collections.Generic.List(Of Figure) 
    Public Shadows Sub Add(ByVal nieuweFiguur As Figure) 
     MyBase.Add(nieuweFiguur) 
     Me.Sort() 
    End Sub 
    End Class 
    Class Client 
    Public Shared Sub Main() 
     Dim figures As New Figures 
     figures.Add(New Figure With {.Area = 12}) 
     figures.Add(New Figure With {.Area = 16}) 
     '*********************************************************** 
     figures.Sort() 'i want to hide the sort method to the client 
     '*********************************************************** 
    End Sub 
    End Class 
End Namespace 

回答

2

很簡單,如果你不想呼叫者可以使用你的類的實例,就好像它是基類的實例,你不應該有繼承關係入手 - 它打破了Liskov Substitution Principle

我強烈懷疑Figures應該使用組成,而不是繼承的 - 所以它必須,而不是從中獲取的List(Of Figure)私人領域,你會暴露你要哪個操作,並只有那些操作。大多數操作可能只是委託給列表。

+0

謝謝喬恩,我走錯了路,你展示了正確的方式 – peter 2013-03-08 21:15:50