c# - How to add to a queue via references without changing references accidently?
问题描述
I have a series of way points that are classes. They inherit mono behaviours so they cannot be structs, plus they have behaviours depending on the derived type of way point.
I add each waypoint an AI visits to the queue so they don't wander back to a previous visited one.
How ever, if i now change the AI's CurrentWaypoint
to the next one he arrives at, this changes the one in the queue. So i end up with a queue of all the same waypoint reference.
How can i prevent this but still be able to check if CurrentWaypoint
exists in the queue via reference checks ? I believe if i just use a copy then the reference checks will fail so thats not good either.
My two methods are:
private bool HasVisited(Waypoint wp)
{
if (_previousVisits.Contains(wp))
{
return true;
}
return false;
}
private void AddVisited(Waypoint wp)
{
// we only need the last 2 wp's visited
if (_previousConnections.Count > 1)
{
_previousConnections.Dequeue();
}
_previousVisits.Enqueue(wp);
}
Whats the best solution to this problem ?
解决方案
To do so, I would build a wrapper class around Waypoint to provide my own comparison such as:
public class WaypointWrapper
{
private readonly Vector3D _waypointPosition;
public WaypointWrapper(Waypoint waypoint)
{
/* Assuming the Waypoint class has a position property that is a Vector3D struct */
_waypointPosition = waypoint.position;
}
public override Equals(object obj)
{
var otherWaypointWrapper = obj as WaypointWrapper;
if(otherWaypointWrapper == null)
return false;
return otherWaypointWrapper._waypointPosition.Equals(_waypointPosition);
}
public override int GetHashCode()
{
return _waypointPosition.GetHashCode();
}
}
推荐阅读
- android - 如何在安卓应用中打开前置摄像头
- css - -webkit-pictograph 不适用于 safari
- r - 让 Shinyapp 跨会话使用新输入
- c# - 如何在c#中从ffmpeg进程获取输出
- sql - DB2 SQL - 检索字段的最大值以及其他字段
- wordpress - 如何修复 GTMetrix 在 wordpress 中显示外部 url 的 Minify JavaScript 选项
- scala - scala REPL启动时如何自动将用户定义的包导入scala REPL?
- html - AngularJS按显示值而不是接收到的数据/json值搜索?
- android - 删除的子模块仍在更新
- php - 如何测试本地主机中的 Facebook 登录按钮?