我试图找出在我正在创建的嵌套类中设置和获取属性的最佳方法.
我有一个类,Car有一个嵌套类ControlPanel,并希望使控制面板的属性只能访问Car和Control Panel类.
(即:不在程序集或命名空间内,不在应用程序中将使用类库)…我已将类访问属性更改为朋友,受保护的朋友,私有,公共,但任何组合都不匹配我的预期结果.
我想更改类的Drive()Sub中的属性,如下所示.
有什么想法吗?
Public Class Car Dim cp As New ControlPanel Public Class ControlPanel Private _Speedometer As Integer = 0 Private _Odometer As Integer = 0 Public Property Speedometer() As Integer Get Return _Speedometer End Get Protected Set(ByVal value As Integer) _Speedometer = value End Set End Property Public Property Odometer() As Integer Get Return _Odometer End Get Protected Set(ByVal value As Integer) _Odometer = value End Set End Property End Class Public Sub Drive() cp.Odometer = 76323 co.Speedometer = 86 End Sub End Class
你可以这样做:
Public Class Car Private Interface IControlPanel Property Odometer As Integer Property Speedometer As Integer End Interface Public Class ControlPanel Implements IControlPanel Public ReadOnly Property Odometer As Integer Get Return CType(Me,IControlPanel).Odometer End Get End Property Public ReadOnly Property Speedometer As Integer Get Return CType(Me,IControlPanel).Speedometer End Get End Property Private Property IControlPanel_Odometer As Integer Implements IControlPanel.Odometer Private Property IControlPanel_Speedometer As Integer Implements IControlPanel.Speedometer End Class Dim cp As IControlPanel = New ControlPanel() Public Sub Drive() cp.Odometer = 76323 cp.Speedometer = 86 End Sub End Class
它使用嵌套在Car类中的私有接口与ControlPanel中的私有实现和别名成员.这样,只有Car可以访问界面成员.