使用泛型和向上转换的最佳方法

时间:2019-11-24 19:12:09

标签: c# generics casting

我具有以下对象,用于执行某些地图导航逻辑:

public interface Node
{
    //.. PathFinder needs this stuff
}

public class MapTile : Node
{
    //.. PathFinder doesn't need this stuff
}

public interface Pathable<T> where T : Node
{
    //.. contains contextual information related to movement that the path finder needs, like whether the agent is walking or flying
}

public class WalkAction : Pathable<MapTile>
{
    //.. PathFinder doesn't need this stuff
}

public static class PathFinder
{
    public static void FindPath(Node start, Node end, Pathable<Node> context)
    {
         //.. logic to find the path
    }
}


public void main()
{   
    WalkAction walkContext = CreateWalkContext();        
    MapTile[] map = CreateMap();
    PathFinder.FindPath(map[0], map[42], walkContext);
}

编译器抱怨我使用“ PathFinder.FindPath”,因为无法将WalkAction类型的对象转换为Pathable

从概念上讲,这是为什么?如果我想让寻路逻辑(应该只处理节点和一些上下文信息)与我更具体的实现逻辑清晰地分开,是否有一种更聪明的结构方式?

0 个答案:

没有答案