C#中如何读取Hashtable的所有值?代码问题求助
问题分析与修复
核心问题
- 遍历逻辑错误:你当前的循环里,
monsters.Keys会输出Hashtable的所有键集合,而非当前迭代项的键;直接遍历DictionaryEntry对象会遍历它的Key和Value属性,而不是你存在值里的数组元素。 - 随机选择未使用:生成的
selection列表(10个随机键)完全没用到,代码反而遍历了整个Hashtable。 - 非泛型容器的弊端:
Hashtable是旧的非泛型容器,访问值时需要强制类型转换,容易引发类型错误,建议改用泛型的Dictionary<int, int[]>,类型更安全。 - 初始化代码冗余:手动声明50个数组的写法极度繁琐,完全可以用循环批量生成。
修复后的代码
using System; using System.Collections.Generic; using System.Linq; namespace CardGame { internal class Program { static Dictionary<int, int[]> monsters; // 改用泛型Dictionary static void Main(string[] args) { monsters = new Dictionary<int, int[]>(); // 用循环批量初始化卡牌,避免重复代码 // 定义各类型卡牌的数值和数量 var cardTemplates = new List<(int value1, int value2, int count)> { (1, 2, 9), (1, 4, 1), (2, 4, 10), (3, 6, 10), (4, 8, 10), (5, 10, 10) }; int cardId = 1; foreach (var template in cardTemplates) { for (int i = 0; i < template.count; i++) { monsters.Add(cardId++, new int[] { template.value1, template.value2 }); } } Random rand = new Random(); // 生成10个不重复的随机键 var selection = Enumerable.Range(1, 50).OrderBy(x => rand.Next()).Take(10).ToList(); // 遍历随机选中的键,输出对应卡牌 foreach (var key in selection) { if (monsters.TryGetValue(key, out int[] card)) { Console.WriteLine($"卡牌编号 {key}:"); Console.WriteLine($"属性1: {card[0]}, 属性2: {card[1]}"); Console.WriteLine("---"); } } } } }
关键修改说明
- 改用泛型Dictionary:
Dictionary<int, int[]>明确了键是int类型,值是int数组,避免了类型转换的麻烦和错误。 - 批量初始化:用模板列表+循环生成50张卡牌,代码简洁易维护,后续修改卡牌数值或数量只需调整模板即可。
- 正确使用随机选择:遍历生成的
selection列表,通过TryGetValue安全获取对应卡牌(避免键不存在的异常)。 - 正确输出数组元素:直接访问数组的索引,输出卡牌的两个属性,而不是错误地遍历DictionaryEntry对象。
内容的提问来源于stack exchange,提问作者Owain
相关产品推荐
相关产品推荐

