有一个关系封装

时间:2015-12-27 16:31:38

标签: c# .net oop inheritance encapsulation

基类是否可以访问继承类中的字段(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;
}

也许有一些棘手的事情我不知道如何管理,或者最好是创建一些更聪明的类层次结构。无论如何,提前谢谢你。 很抱歉missunderstanding。在几句话中,我有一个类游戏,其中包括另一个类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().

1 个答案:

答案 0 :(得分:1)

如果您想继续使用现有的代码,可以在public string GetName()中定义InheritedClass函数,然后从BasicClass <中创建的对象中调用它/ p>

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