C#中UInt32与Int32引发的HashTable访问异常问题求助
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
Int32is a different type than a boxedUInt32, 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 returnsnull—no further numeric comparison happens.
In your case:
- Originally, you stored keys as
int(boxedInt32). - After your change, you're trying to look up with
UInt32(boxedUInt32). Even whenHashEntryis0x00000000, the boxed types don't match, soHashTablecan'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 toUInt32(even if they're numeric literals like0). - When looking up, always use a
UInt32key (don't mixInt32andUInt32).
Quick Recap
- Non-generic collections like
HashTablerely on object boxing, which makes type identity critical for key lookups. Int32andUInt32are distinct types—their boxed versions won't be considered equal, even with the same numeric value.- Generic collections like
Dictionaryeliminate this problem by enforcing type safety at compile time.
内容的提问来源于stack exchange,提问作者Steven Burck

