gpt4 book ai didi

c# - 类修饰符

转载 作者:行者123 更新时间:2023-11-30 21:05:38 25 4
gpt4 key购买 nike

我从来没有主动学习过正确的类修饰符,因为它一直是“拥有很好”而不是“必须拥有”。

令我烦恼的是我可以做 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),然后将实现标记为私有(private)。

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

关于c# - 类修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11587515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com