我从来没有主动学习正确的类修饰符,因为它一直是“很高兴”但不是“需要”。
我可以做Dim F as New Person.FavoriteFoodsList
令我很烦。
我使用哪个类修饰符,以便我的Person类可以利用FavoriteFoodsList,但Person之外的任何实例都不能实例化FavoriteFoodsList?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim P As New Person
P.FavoriteFoods.Add("Pizza")
Dim F As New Person.FavoriteFoodsList 'How do I prevent this
End Sub
Public Class Person
Public FavoriteFoods As New FavoriteFoodsList
Public Class FavoriteFoodsList
Inherits Collections.Generic.List(Of String)
End Class
End Class
最佳答案
我建议您为类定义一个公共接口,然后将实现标记为私有。
Public Interface IFavoriteFoodsList
Inherits Collections.Generic.IList(Of String)
' Define other public api methods'
End Interface
Public Class Person
Public FavoriteFoods As IFavoriteFoodsList = New FavoriteFoodsList
Private Class FavoriteFoodsList
Inherits Collections.Generic.List(Of String)
Implements IFavoriteFoodsList
End Class
End Class