似乎无法从界面投射到我的结构以获得列表

时间:2020-08-28 04:32:22

标签: c#

我有一个函数返回一个名为IPathfindingNode的接口的列表。

我创建了一个实现接口的结构:

public struct Node : IPathfindingNode
{
    public int X { get; }
    public int Y { get; }
}

我调用一个返回接口列表的函数:

public List<IPathfindingNode> FindPath(Vector2Int startPoint, Vector2Int targetPoint)

当我尝试分配结果时,我收到一条错误消息,说我无法将其分配给我的列表,但我不明白为什么。

List<Node> path = Map.FindPath(startPoint, targetPoint);

我收到此错误:

无法隐式转换类型 'System.Collections.Generic.List <路径查找.IPathfindingNode>' 到'System.Collections.Generic.List '

我该如何正确投放?我尝试了as List<Node>();,但仍然无法正确转换。

1 个答案:

答案 0 :(得分:4)

不管其他任何问题,您都可以使用Cast

将IEnumerable的元素转换为指定的类型。

List<Node> path = Map.FindPath(startPoint, targetPoint)
                     .Cast<Node>()
                     .ToList()

如果FindPath返回了Node的其他非IPathfindingNode实现,则可以使用OfType

根据指定的类型过滤IEnumerable的元素。