【问题标题】:An alternative to List.Contains for custom classes用于自定义类的 List.Contains 的替代方案
【发布时间】:2017-11-05 15:56:54
【问题描述】:

我正在尝试使用 A* 进行寻路,并创建了一个“节点”类。

关键是我有一个节点列表,我需要知道一个节点是否已经在列表中,但是 List.Contains 不起作用。

顺便说一句,我需要比较 Node 内变量中的世界位置,但我不知道如何覆盖 List.Contains 以与该变量进行比较。

编辑:添加了尝试实现 Equals 和 HashSet 的 Node 类

using System.Collections;
using UnityEngine;
using System.Collections.Generic;

public class Node {

public Node parentNode;

public int nodeX;
public int nodeY;
public Vector2 nodePosition;

public bool state;

public int gCost;
public int hCost;
public int fCost;

public Node(int x, int y){
    nodeX = Mathf.RoundToInt(x);
    nodeY = Mathf.RoundToInt(y);
    nodePosition = new Vector2(nodeX, nodeY);
}

public void SetCost(Node end){
    if(parentNode != null){
        gCost =(int) parentNode.gCost + 10;
    }
    else{
        gCost = 10;
    }

    hCost =(int) (Mathf.Abs(nodeX - end.nodeX) + Mathf.Abs(nodeY-end.nodeY));
    fCost =(int) gCost + hCost;
}

public bool Equals (Node other){
    if(other == null){return false;}
    if(this.nodePosition == other.nodePosition){return true;}
    else{return false;}

}

public override bool Equals(Object other){
    if(other == null){return false;}
    if(other is Node){
        return this.Equals(other);
    }
    else{
        return false;
    }
}

public override int GetHashCode(){
    return nodeX ^ nodeY;
}

【问题讨论】:

    标签: list contains path-finding


    【解决方案1】:

    对于开放集,您应该使用priority queue。对于封闭集,只需为每个节点添加一个属性HasBeenVisited。 A* 不需要List

    【讨论】:

    • 问题是当我在寻找创建它们的邻居节点时。因此,如果存在具有相同位置的节点,则不创建新节点的唯一方法我真的不知道如何比较要创建的节点是否已经在该位置有一个节点。但是关于优先队列我什么都没看到,所以我会检查一下
    • 在这种情况下,您可能需要HashSet。如果等效节点不被视为相等,您也会遇到同样的问题,因此请查看如何正确实现 EqualsIEquatable<T>
    • 这就是我一直在做的。但是我在任何地方都看不到如何覆盖 Equals 和 HashSet 的体面解释。我已经尝试过了,但不起作用,但我不知道我是否做错了什么,所以我将编辑问题并添加 Node 类代码。
    • @Luxgile:请将其发布到 codereview.SE,该代码存在太多问题,无法在此处列举。我相信您的主要问题是 return this.Equals(other); 没有转换为 Node
    • 对不起,但我实际上不知道什么是 codereview.SE。我希望当你说很多问题时,你会谈论覆盖函数和那些东西......
    猜你喜欢
    • 2019-01-23
    • 2023-03-10
    • 2011-07-18
    • 1970-01-01
    • 2010-11-13
    • 2020-02-09
    • 1970-01-01
    • 2015-07-14
    • 2011-05-24
    相关资源
    最近更新 更多