【问题标题】:Hide the sort of a collection in VB.NET在 VB.NET 中隐藏集合的种类
【发布时间】:2013-03-08 20:32:17
【问题描述】:

在以下示例中,我想向客户端隐藏 .sort() 方法,我该如何实现?

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

【问题讨论】:

    标签: vb.net interface encapsulation icomparable


    【解决方案1】:

    很简单,如果您不希望调用者能够像使用基类的实例一样使用您的类的实例,那么您一开始就不应该有这种继承关系 - 它会破坏Liskov Substitution Principle.

    我强烈怀疑Figures 应该使用组合而不是继承 - 所以它会有一个 List(Of Figure) 的私​​有字段而不是从它派生,并且你会公开你想要的任何操作,并且 那些操作。大多数操作可能只是委托给列表。

    【讨论】:

    • 谢谢乔恩,我走错了路,你的方法是正确的
    猜你喜欢
    • 2015-01-21
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 2013-02-18
    相关资源
    最近更新 更多