如何比较两个哈希表
我正在用 C#(使用 XNA)开发一个小型 RTS。
我将每个单元的“goto”位置设置为它们应该去的向量。如果我不比较两个哈希表,一切都会正常,但是当我这样做时,我会收到“NullReferenceException 未处理”的烦人错误。
这是我遇到错误的代码片段:
if (
((float)unit[(int)selectedunits[I+"ID"] + "posX"] !=
(float)cgoto[(int)selectedunits[I+"ID"] + "X"])
&&
((float)unit[(int)selectedunits[I+"ID"] + "posY"] !=
(float)cgoto[(int)selectedunits[I+"ID"] + "Y"])
)
希望这足够具体。
I am developing a small RTS in C#(with XNA).
I'm setting each unit "goto" position as the vector they should go to. Everything works fine if I don't compare the two Hashtables, but when I do, I get this "NullReferenceException was unhandled" annoying error.
Here's the piece of code I'm getting the error on:
if (
((float)unit[(int)selectedunits[I+"ID"] + "posX"] !=
(float)cgoto[(int)selectedunits[I+"ID"] + "X"])
&&
((float)unit[(int)selectedunits[I+"ID"] + "posY"] !=
(float)cgoto[(int)selectedunits[I+"ID"] + "Y"])
)
Hopefully this is specific enough.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
遗憾的是,这里没有足够的信息可以继续。您在代码行中使用的引用类型之一在执行时为 null。您可以做的是在该行上设置断点,并在调试模式下执行。当执行流程到达该行时,您可以检查正在使用的所有引用以查看哪一个为空,然后从那里诊断它为何为空。
Sadly, there isn't enough information to go on here. One of your reference types you're using in your line of code is null at the time of execution. What you can do is set a breakpoint on that line, and execute in debug mode. When the flow of execution hits that line, you can examine all of the references you're using to see which one is null and then diagnose the why it's null from there.
您提供的哈希表值比较没有问题。铸造方面存在一些问题和一些总体设计点。我相信您在尝试将 null 转换为
float
/int
时遇到了此类异常,为避免此类问题,请使用 Hashtable.ContainsKey() 方法检查哈希表中是否存在给定的键,然后才访问它的值。不要忘记在转换之前检查值是否为 null。您也可以考虑使用通用类型IDictionary
(参见 MSDN),因此所有值都将被键入,并且您不需要显式转换,这也会带来一些性能提升,因为不再像您的示例中那样对值类型进行装箱<代码>浮动-> object 当存储值时和object ->检索并投射时浮动
(拆箱)。There are not problems in hashtable values comparision you've provided. There some issues with casting and some general design points. I believe you got such exception when trying to cast null to
float
/int
, to avoid such issues use Hashtable.ContainsKey() method to check whether a given key exist in a hashtable and only then acces it's value. Do not forget checking a value for null before cast. Also you can consider using generic typedIDictionary<string, float>
(see MSDN) so all values would be typed and you do not need to cast explicitly, this also would give some perfromance gains since no more boxing for value types like in your examplefloat -> object
when store a value andobject -> float
(unboxing) when retrieve back and cast.