c# -对象变量赋值失败
本文关键字:赋值 失败 变量 对象 | 更新日期: 2023-09-27 18:13:24
我很难理解为什么我的变量有一个空值。
这是我的类构造函数:
private GraphNode current;
private GraphNode goal;
private GraphNode start;
private List<GraphNode> path;
private List<GraphNode> origin;
public Graph()
{
current = new GraphNode(0, 0);
goal = new GraphNode(0, 0);
start = new GraphNode(0, 0);
path = new List<GraphNode>();
origin = new List<GraphNode>();
}
方法setpath的定义:
public void SetPathing(int mouseX, int mouseY)
{
if (Contains((int)mouseX / 32, (int)mouseY / 32))
{
goal = GetNode((int)mouseX / 32, (int)mouseY / 32);
current = goal;
path.Add(current);
while ((current.X != start.X) && (current.X != start.X))
{
current = origin.Where(keyValuePair => (keyValuePair.Key.X == current.X) && (keyValuePair.Key.X == current.Y)).Select(keyValuePair => keyValuePair.Value).LastOrDefault();
path.Add(current);
}
}
}
当我在setpath中的while循环开始时中断时,我在locals屏幕中看到以下信息:
current null PathFinding.GraphNode
goal {PathFinding.GraphNode} PathFinding.GraphNode
X 0 int
x 0 int
Y 5 int
y 5 int
在明确地将目标的参考值赋给当前之后,这怎么可能呢?
我可能错过了一些愚蠢的东西,但我找了两个小时也没有找到。这里没有异步操作
EDIT:我不想在我最初的问题上过于冗长,这里有一些额外的细节,我的道歉。下面是Contains, GetNode和GetNodeIndex的详细信息。没什么特别的,我是个业余爱好者。
public int GetNodeIndex(int x, int y)
{
// Find the node index in the list based on x and y
// Return -1 if not found
return nodes.FindIndex(n => (n.X == x) && (n.Y == y));
}
public GraphNode GetNode(int x, int y)
{
// Find the node in the list based on x and y
// Return null if not in list
int nodeIndex = GetNodeIndex(x, y);
if (nodeIndex != -1)
{
return nodes[nodeIndex];
}
return null;
}
public bool Contains(int x, int y)
{
// Check if the returned value is not -1
if (GetNodeIndex(x, y) != -1)
{
return true;
}
}
这个用例实际上只是沿着下面的行:
using System;
namespace Graphs
{
class Program
{
static void Main()
{
Graph graph = new Graph(20, 20);
graph.SetPathing(Mouse.GetState().X, Mouse.GetState().Y);
}
}
}
让我们仔细分析一下你的代码。
goal = GetNode((int)mouseX / 32, (int)mouseY / 32);
goal -> A
current -> null
接下来,执行以下操作:
current = goal;
现在,你的值看起来像这样:
goal -> A
current -> A
在你的while循环中,你调用这个:
current = origin.Where(keyValuePair => (keyValuePair.Key.X == current.X) && (keyValuePair.Key.X == current.Y)).Select(keyValuePair => keyValuePair.Value).LastOrDefault();
为简单起见,我们将此结果称为where子句b。因此,现在您的值看起来像这样:
goal -> A
current -> B
您在这里所做的只是将current
指向一个新值。
您展示了默认图形构造函数的代码
public Graph()
不是正在使用的那个
Graph graph = new Graph(20, 20);
它们之间有什么区别吗?
另外,您确定您的代码与程序集同步吗?也就是说,从你的描述来看,你的断点似乎在这一行
while ((current.X != start.X) && (current.X != start.X))
你确定当你调试的时候,当调试器停止时,它确实只执行到这里,或者它可能已经执行了两行以下的过滤代码?
我不确定这是怎么可能的,但答案似乎是,这实际上不是while循环的第一次迭代。
我将断点设置为循环,并且我上面发布的结果来自该断点的第一次命中。然而,在添加了一个作为迭代计数器的变量之后,事实证明这实际上不是第一次迭代,而是第三次迭代。在这个发现之后,我继续改进while循环中的代码,以防止current被设置为null。
我不知道这是怎么发生的。我正在使用Visual Studio 2013 Express for Desktop。