2012-07-20 45 views
2

我從來沒有主動去學習正確的班級修改器,因爲它一直是「很高興有」,而不是「需要有」。班級修改器

這讓我很煩,我可以做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 

回答

2

我建議您爲您的類定義一個公共接口,然後將該實現標記爲私有。

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 
+0

謝謝先生。那就是訣竅!我會盡快接受答案。它說我必須再等3分鐘 – DontFretBrett 2012-07-20 22:12:36

+0

實際上,它和phoog的答案有點相同。您也不能從phoog的解決方案實例化FavoriteFoodsList。 但是,我覺得這個更好一些,因爲界面是在Person類之外定義的,因爲在phoog的答案中,有一個嵌套的公共類,這不是那種'友好'的imho。 – 2012-07-20 22:13:54

+0

在phoogs答案我不能添加食物的名單。我嘗試了P.FavoriteFoods.Add,沒有Add方法可用。 *編輯,我想因爲我沒有繼承列表? – DontFretBrett 2012-07-20 22:14:48

2

編輯3:移除了這個答案是嘗試申請低於私有/ protected成員圖案的早期版本:

爲了說明這是如何跨越組件邊界工作,這裏有一個例子:

public class Person 
{ 
    public abstract class FavoriteFoodsList : List<string> 
    { 
     //internal constructor prevents types in other assemblies from inheriting 
     internal FavoriteFoodsList(){} 
    } 
    private class FFL2 : FavoriteFoodsList 
    { 
    } 
    public FavoriteFoodsList FavoriteFoods = new FFL2(); 
} 

免責聲明,這只是一個草圖來說明可訪問性問題;該字段應該是屬性等。

+0

我嘗試了你的建議,當我鍵入P時,我可以看到FavoriteFoods和FavoriteFoodsList。我無法將任何東西添加到 – DontFretBrett 2012-07-20 22:10:21

+0

確定您可以看到FavoriteFoodsList。如果你想能夠使用這個類,那麼'base'類必須是可見的。 – 2012-07-20 22:12:28

+0

@DontFretBrett感謝翻譯;我已將它添加到答案中。 – phoog 2012-07-20 22:12:55

0

沒有類修飾符或輔助功能修飾符可以讓您在一個程序集中完成此操作。與其他答覆者所說的一個私有實現類的接口可能是最好的解決方案。但是,如果你正在編寫一個類庫,你可以聲明所有的FavoriteFoodsList的構造函數爲internal(在VB中爲Friend,我想),並且這將阻止其他程序集構造它們自己的FavoriteFoodsList對象。

+0

我會在下次嘗試這樣做。謝謝! – DontFretBrett 2012-07-20 22:23:26