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

为什么C#遍历Dictionary的foreach循环需用KeyValuePair而非Dictionary作为类型

问题原因解释

C# 中foreach迭代的类型由目标集合实现的IEnumerable<T>接口的泛型参数决定:

  • Dictionary<TKey, TValue>本身实现的是IEnumerable<KeyValuePair<TKey, TValue>>接口,这意味着字典存储的每一个独立元素都是KeyValuePair<TKey, TValue>类型的键值对结构体,而非Dictionary<TKey, TValue>类型,所以你在循环中直接指定元素类型为Dictionary<int,string>会触发类型不匹配的编译错误。
  • 另外你提供的示例代码存在一处笔误:new Dictionary<int string>()中两个泛型参数之间缺少逗号,正确写法是new Dictionary<int, string>()。
正确写法

如果不想用var、要显式指定元素类型,修改后的代码如下:

Dictionary<int, string> names = new Dictionary<int, string>();

names[10] = "some test";
names[11] = "another text";

foreach(KeyValuePair<int,string> name in names)
{
    Console.WriteLine($"键:{name.Key},值:{name.Value}");
}
补充说明

如果只需要遍历字典的键或者值,也可以单独遍历对应的属性:

  • 遍历所有键:foreach(int key in names.Keys)
  • 遍历所有值:foreach(string value in names.Values)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 02:06:01