2015-12-27 41 views
0

基類是否可以訪問繼承類中的字段(has-a relationship)?有關係封裝

class BasicClass 
{ 
    public InheritedClass objTemp = new InheritedClass(); 
    public BasicClass() 
    { 
    //Now i want to get some information from objTemp fields. 
    //But Name is protected, what should I do here? 
     objTemp.Name.Length(); 
    } 
} 
class InheritedClass 
{ 
    protected string Name; 
} 

也許有一些技巧性的東西,我不知道如何來管理,或者也許是更好地創造一些更聰明的類層次結構。無論如何,先謝謝你。 抱歉誤會。用幾句話說,我有班級遊戲,其中包括另一個類WordsContainer。

class Game 
{ 
    private Player objGamer; 
    private WordsContainer objWordsClass = new WordsContainer(); 
    public Game() 
    { 
     Console.Title = "Hangman"; 
     Console.Write("Player name information:"); 
     string localName = Console.ReadLine(); 
     objGamer = new Player(localName); 
     StringBuilder bumpWord = new StringBuilder(objWordsClass.getKeyWord().Length); 

    } 
class WordsContainer 
{ 
    /// <summary> 
    /// WordsContainer class contains a list of strings from wich with getKeyWord method 
    /// we could get string type key. 
    /// </summary> 
    private List<string> wordBank = new List<string>() {"stack","queue","heap","git","array"}; 
    public WordsContainer(){} 
    public string getKeyWord() 
    { 
     Random random = new Random((int)DateTime.Now.Ticks); 

     return wordBank[random.Next(0, wordBank.Count)]; 
    } 

那麼,是否可以以這種方式在某種程度上隱藏public string getKeyWord().

+0

如果要公開訪問名稱,請使用「公共」訪問修飾符。它不應該根據您的設計進行保護。 –

+1

你爲什麼需要這個?當你需要時,你能帶來真實的例子/案例嗎?也許你做的一切都是錯的。 'protected'不能這樣工作。它從'基地 - >繼承'的'上 - 下'而不是相反。 – Michael

+0

我剛剛使用Name作爲實例。在我想要訪問的我的InheritedClass字段中必須受到保護。 – What

回答

1

如果要繼續進行下去,你現在的代碼,你可以只在InheritedClass定義public string GetName()功能和從對象稱呼它您在BasicClass中創建

class BasicClass 
{ 
    public InheritedClass objTemp = new InheritedClass(); 
    public BasicClass() 
    { 
     int nameLength = objTemp.GetName().Length(); 
    } 
} 
class InheritedClass 
{ 
    protected string Name; 
    public string GetName() 
    { 
     return Name; 
    } 
}