c#如何找到同一个多态链的兄弟

c# How to find the sibling of the same polymorphic chain

我不太确定如何描述这个问题,但会试一试并在此过程中进行编辑。

我有一个多态代码结构:

  1. public 接口 IFoodItem

  2. public 接口 IFruitItemModel : IFoodItem

3a。 public class PooledFruitItem : IFruitItemModel

3b。 public 接口 IJuiceModel : IFruitItemModel

3c。 public 接口 IPieModel : IFruitItemModel

4a。 public class 果汁模型:IJuiceModel

4b。 public class 饼图模型:IPieModel

希望你清楚这个结构。

每次单击项目、果汁或馅饼时,代码都会向我发送一条消息。

在return我需要在游戏中“显示”点击的项目。

消息中的项目是 PooledFruitItem 类型的 IFruitItemModel。 我需要拿这个项目并将它连接到“JuiceModel”或“PieModel”之一

这是代码:

    private void ShowFruitItem(IFruitItemModel fruitModel) {
        if (fruitModel is IPieModel) {
            table.SetPie((fruitModel as IPieModel).PieObject);
        } else {
            table.SetJuice((fruitModel as IJuiceModel).JuiceTexture);
        }
    }

我使用此方法的问题是 PooledFruitItem 类型的 fruitModel 找不到与 JuiceModel 的连接,即使它们具有相同的父级。

3a可以吗? PooledFruitItem,找到通往 4a 的路。 IJuiceModel?

谢谢

这是到达 IJuiceModel 的层次结构...

IFoodItem <- IFruitItemModel <- IJuiceModel

但是,这是 PooledFruitItem 的层次结构...

IFoodItem <- IFruitItemModel <- PooledFruitItem

它没有class化为果汁的原因是因为 PooledFruitItem 没有实现 IJuiceModel!

为此,您需要:

IFoodItem <- IFruitItemModel <- IJuiceModel <- PooledFruitItem

...或 class 形式:

//*** NOT this ***
public class PooledFruitItem : IFruitItemModel {}

//*** THIS ***
public class PooledFruitItem : IJuiceModel {}

另请注意,在某些情况下,您的转换将失败并且 return 为 null:

else {
        //*** All we know here is is that we don't have an IPieModel, 
        //*** but that doens't necessarily mean we have an IJuiceModel
        //*** That means "fruitModel as IJuiceModel" may return null.
        table.SetJuice((fruitModel as IJuiceModel).JuiceTexture);
    }

鉴于您所述的结构,这更有意义:

private void ShowFruitItem(IFruitItemModel fruitModel) 
{
    if (fruitModel is IPieModel) 
        DoPie(fruitModel as IPieModel);
    else if (fruitModel is IJuiceModel)
        DoJuice(fruitModel as IJuiceModel);
    else
        DoFruit(fruitModel);
}