在课堂之外,我希望能够以ReadOnly的身份访问CCTV.Camera.Brightness属性,但CCTV类中的方法应该能够修改Brightness属性。请问您如何实现这一目标?
我认为我需要添加一个公开某些属性并隐藏其他属性的接口,但我不确定实现。 [注意构造函数和main sub显然是为这个例子和测试而设计的。
Public Class CCTV
Public Class Camera
Public Property Name as String
Public Property Brightness as Integer
End Class
Dim cameras as New Dictionary(Of String, Camera)
Public Sub New()
Dim cam As New Camera
cam.Name = "driveway"
cam.Brightness = 5
cameras.Add(cam.Name, cam)
End Sub
Public Sub ChangeBrightness(value as Integer)
cameras("driveway").Brightness = value
End Sub
End Class
Sub main()
Dim MyCCTV = new CCTV
MyCCTV.ChangeBrightness(10)
if MyCCTV("driveway").Brightness = 10 then Console.Write("Brightness is 10")
End Sub
答案 0 :(得分:1)
获取getter并且属性的setter可以具有不同的可访问性修饰符。在这种情况下,您希望每个人都可以读取Brightness,但只有您信任的代码才能编写它。你这样做:
Public Class Camera
Private _brightness As Integer
Public Property Brightness As Integer
Get
Return _brightness
End Get
Friend Set(value As Integer)
_brightness = Value
End Set
End Property
'' etc...
End Class
请注意添加的Friend
关键字,它限制了对Camera类所属的同一项目中的代码的访问权限。如果要限制只访问Camera类或其派生类中的代码,它也可以是Private
或Protected
。
答案 1 :(得分:0)
在这种情况下不需要任何接口。您只需要以readonly方式创建属性。当您将属性设置为readonly时,假设该值将存储在私有变量中,并且此时应该更好地传递它或者方法或使用重载方法的subnew让我给你举个例子:
Public Class CCTV
Public Class Camera
Private _Name As String
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Private _Brightness As String
Public ReadOnly Property Brightness() As String
Get
Return _Brightness
End Get
End Property
''' <summary>
''' Defautl sub new method
''' </summary>
''' <remarks></remarks>
Sub New()
End Sub
''' <summary>
''' second overload
''' </summary>
''' <param name="cameraName"></param>
''' <param name="brightness"></param>
''' <remarks></remarks>
Sub New(ByVal cameraName As String, ByVal brightness As Integer)
Me.Name = cameraName
Me._Brightness = brightness
End Sub
''' <summary>
''' Change brigthness
''' </summary>
''' <param name="value"></param>
''' <remarks></remarks>
Public Sub setUpCameraBrightness(ByVal value As Integer)
'take care to use private varibale so it will reflcet changes into propetry readonly
Me._Brightness = value
End Sub
End Class
Dim cameras As New Dictionary(Of String, Camera)
Public Sub New()
'two differnet approach
'first overaload:
Dim cam As New Camera()
cam.Name = "yourcamname"
cam.setUpCameraBrightness(10)
cameras.Add(cam.Name, cam)
''second approch declarative value:
Dim cam2 As New Camera("yourcamname", 10)
cameras.Add(cam2.Name, cam2)
End Sub
Public Sub ChangeBrightness(value As Integer)
cameras("driveway").setUpCameraBrightness(100)
End Sub
End Class
Sub main()
Dim MyCCTV = New CCTV
MyCCTV.ChangeBrightness(10)
If MyCCTV("driveway").Brightness = 10 Then Console.Write("Brightness is 10")
End Sub