You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中UInt32与Int32引发的HashTable访问异常问题求助

Why HashTable Fails with UInt32 Keys (But Works with Int32)

Hey Steven, this is a super common pitfall with .NET's non-generic HashTable—let's unpack exactly what's going on here:

The Core Issue: Boxing & Type Identity

HashTable stores keys as object (the base type for all .NET types). When you use value types like Int32 or UInt32 as keys, they get boxed (wrapped in an object instance) to be stored. Here's the critical part:

  • A boxed Int32 is a different type than a boxed UInt32, even if their numeric values are identical.
  • When you look up a key in HashTable, it first checks if the types of the lookup key and stored key match. If they don't, it immediately returns null—no further numeric comparison happens.

In your case:

  • Originally, you stored keys as int (boxed Int32).
  • After your change, you're trying to look up with UInt32 (boxed UInt32). Even when HashEntry is 0x00000000, the boxed types don't match, so HashTable can't find the entry.
  • When you switch back to Int32, the lookup key's type matches the stored key's type, so the lookup works.

Why hex_segments[0] Worked

When you write hex_segments[0], the literal 0 is implicitly typed as int (boxed Int32), which matches the type of the keys you originally stored. That's why it found the entry—same type, same value.

Fixes for Your Scenario

Since you're working with unsigned 32-bit addresses, here are two clean solutions:

1. Switch to Generic Dictionary<UInt32, HexSegment>

The non-generic HashTable is legacy—use the type-safe Dictionary<TKey, TValue> instead. It avoids boxing entirely and enforces that all keys are UInt32, so you won't run into type mismatches:

// Replace HashTable with Dictionary
Dictionary<UInt32, HexSegment> hex_segments = new Dictionary<UInt32, HexSegment>();

// Lookup will work correctly now
currseg = hex_segments[HashEntry];

2. Ensure Consistent Key Types with HashTable

If you have to keep using HashTable for some reason, make sure every key you store and look up is explicitly a UInt32:

  • When adding entries to hex_segments, cast keys to UInt32 (even if they're numeric literals like 0).
  • When looking up, always use a UInt32 key (don't mix Int32 and UInt32).

Quick Recap

  • Non-generic collections like HashTable rely on object boxing, which makes type identity critical for key lookups.
  • Int32 and UInt32 are distinct types—their boxed versions won't be considered equal, even with the same numeric value.
  • Generic collections like Dictionary eliminate this problem by enforcing type safety at compile time.

内容的提问来源于stack exchange,提问作者Steven Burck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:42:35