【问题标题】:Is there any way to access variables from a child class given a list of objects defined as the parent?给定定义为父对象的对象列表,有没有办法从子类访问变量?
【发布时间】:2012-11-18 23:45:00
【问题描述】:

我目前正在开发一个小游戏,我有一个关于 OOP 实践的问题。 我的问题是,如果您有一个列表或一个父类型的对象数组,是否有任何方法可以访问子类中的变量。

我目前正在学校上 CS 课程,所以我没有我的源代码,但它一直困扰着我,我也不太确定我应该在这里寻找什么,可能是演员?我的 OOP 知识有点分散(除了 Stack Overflow,很难在 OOP 上找到好的资源,如果你知道的话,请指出一个好的教程的方向)但我想实施好的实践,所以我不跑解决未来的问题(这是一个相当大的项目)

让我在这里说明一下我的意思(同样我没有我的消息来源,但它是这样的):

    List<Tile> Tiles = new List<Tile>(); 
    Tiles.add(new Water()); 
    Tiles.add(new Sand()); 

    foreach(Tile tile in Tiles)
    {
         tile.variable_fromsand = 10; //hypothetical, how could I access a public
                                      //member from sand here, if at all
    }

其中水和沙子是基类 Tile 的子类。

很抱歉,如果之前已经回答过这个问题,我不确定我在寻找什么。如果过去已充分回答,请指出正确的线程。

【问题讨论】:

  • 啊,我感觉这是我要找的演员,你们太棒了!我可能已经从这个线程中学到了更多,然后我将在整个 2 小时的编程课上学到更多,谢谢大家

标签: c# oop inheritance casting polymorphism


【解决方案1】:

铸造会起作用。

foreach(Tile tile in Tiles)
{
    if (tile is Sand)
         ((Sand)tile).variable_fromsand = 10; 
}

【讨论】:

【解决方案2】:

你可以尝试投射它,或者只选择Sandtiles:

// if tile is Sand then use casting
foreach(Tile tile in Tiles)
{
     if(tile is Sand)
     {
         ((Sand)tile).variable_fromsand = 10;
     }
}

// select only tiles which are of Sand type
foreach(Sand tile in Tiles.OfType<Sand>())
{
     tile.variable_fromsand = 10;
}

【讨论】:

    【解决方案3】:

    如果我理解正确,Sand 继承自 Tile,并且您希望在遍历 Tiles 列表时读取其中一个属性。

    您可以在 foreach 循环中强制执行此操作:

    var sand = Tile as Sand;
    if (sand != null)
    {
        // do something with the property of Sand.
    }
    

    通过使用as,只有当tile 变量实际上是Sand. 类型时,您才会强制转换为Sand。如果其中有Water 对象,as 将返回null,并且您将不会拥有您正在寻找的房产。

    【讨论】:

      【解决方案4】:

      你可以做这样的事情,但我会质疑抽象。由于您没有具体说明您实际在做什么,因此很难给出“这是您应该回答的问题。”

      foreach(var sand in Tiles.OfType<Sand>())
      {
      }
      

      【讨论】:

        猜你喜欢
        • 2022-12-19
        • 2018-11-08
        • 2011-01-23
        • 1970-01-01
        • 2016-12-27
        • 2018-02-18
        • 2016-03-31
        • 2023-02-15
        • 2020-12-03
        相关资源
        最近更新 更多