【问题标题】:Has-a relationship encapsulationHas-a 关系封装
【发布时间】:2015-12-27 16:31:37
【问题描述】:

基类是否有可能访问继承类中的字段(有关系)?

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 的 Game 类。

 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().

【问题讨论】:

  • 如果要公开访问名称,请使用“public”访问修饰符。根据您的设计,它不应该受到保护。
  • 你为什么需要它?当你需要的时候,你能带来真实的例子/案例吗?也许你一开始就做错了。 protected 不是这样工作的。它来自up-&gt;down,即来自base-&gt;inherited,而不是相反。
  • 我刚刚使用 Name 作为实例。在我想要访问的 InheritedClass 字段中必须受到保护。
  • 你所谓的“继承”类不会以任何方式继承自 Object 之外的任何东西。
  • “has-a”关系中没有“base”和“inherited”。

标签: c# .net oop inheritance encapsulation


【解决方案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;
    }
}

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 2016-03-23
    相关资源
    最近更新 更多