C# Invalid Cast异常(不知道哪里出错了)

C# Invalid Cast exception (I don't know where is the error)

所以,我制作了这个方法来检测按下按钮时玩家前面是否有任何东西,问题是,即使没有 out 参数(它 returns 谁在播放器前面)似乎工作,这个抛出一个无效的转换异常,即使我研究过我仍然不知道这里有什么问题。

有问题的函数代码:

public bool isThereAnythingThere(Rectangle rec, out NPC other) {
    bool tmp = false;
    other = null;

    foreach (NPC npc in gol)
    {
        if (npc.collider.Intersects(rec))
        {
            tmp = true;
            other = npc;
        }
    }
    return tmp;
}

触发它的播放器函数:

void Action1()
{
    NPC go = null;

    switch (facingDirection) {
        case Direction.Up: if (!game.isThereAnythingThere(UpRectangle), out go) ;
            break;
        case Direction.Down: if (!game.isThereAnythingThere(DownRectangle), out go) ;
            break;
        case Direction.Left: if (!game.isThereAnythingThere(LeftRectangle), out go) ;
            break;
        case Direction.Right: if (!game.isThereAnythingThere(RightRectangle), out go) ;
            break;
        } //Now go equals the object in the direction where facing, if theres no object, is null

        if (go != null)
            game.textBox.AddText(go.GetDialogue());
    }
}

PS:gol是我游戏中所有GameObject的列表; GameObject 是一个 class,PlayerNPC 都继承自它。

您的问题是您正在遍历一个可能包含非 NPC 内容的列表,并告诉 foreach 尝试将所有内容都转换为 NPC

最简单的解决方法是使用 Linq OfType<T> 按类型过滤列表:

foreach (NPC npc in gol.OfType<NPC>())