c# - 为什么Dictionary在这里变成了KeyValuePair?
问题描述
为了理解它们,我只是在弄乱一些 C# 的数据类型。我一直在尝试了解为什么这本字典变成了 KeyValuePair。这是我的代码:
class Program
{
static Dictionary<string, int> operatii(int a, int b)
{
Dictionary<string, int> calculare = new Dictionary<string, int>();
calculare.Add("suma", a + b);
calculare.Add("produs", a * b);
return calculare;
}
static void Main(string[] args)
{
foreach(Dictionary<string, int> dict in operatii(5, 6))
{
Console.WriteLine();
}
}
}
我收到了这个错误:
错误 CS0030 无法将类型 'System.Collections.Generic.KeyValuePair<string, int>' 转换为 'System.Collections.Generic.Dictionary<string, int>'
现在,当我写这篇文章时,我明白我的逻辑有缺陷,foreach 的第一个参数不能是字典。
但是 C# 怎么知道这应该是 KeyValuePair 呢?也许我真的打算在那里写字典,并使 foreach 只运行一次(因为我只有一个字典)。
谢谢。
解决方案
您通过调用来调用枚举器Dictionary
-foreach
并且foreach
将使您能够访问元素。
这是设计使然;见msdn。
foreach (var element in enumerable)
编译器试图告诉你你试图将整个字典压缩在一个元素中:键值对。(注意;这是一个类比:实际原因是类型不匹配,而不是大小。C# 是类型安全的,这意味着您只能将某些内容分配给具有相同类型的类型 - 可能通过继承 - 类型)
就像你foreach
在一个int[]
数组上一样,循环中的元素将是一个int
,而不是数组本身,int[]
。
因此,对于您的代码:
您的方法属于 Dictionary<> 类型:
//the Dictionary is enumerable
//an element is the KeyValuePair
Dictionary<string, int> operatii(int a, int b)
所以,在循环中:
// this should be an element in the enumeratable
foreach(Dictionary<string, int> dict in operatii(5, 6))
或其等价物:
var array = new int[] {1,2,3};
// element is of type ìnt`
foreach(int element in array)
要解决这个问题:
foreach(KeyValuePair<string, int> dict in operatii(5, 6))
推荐阅读
- python - Cloud ML Engine 和 Scikit-Learn:“LatentDirichletAllocation”对象没有“predict”属性
- java - Java IBM-860 编码问题
- javascript - React Context API - 如何在条件方法的提供者中获取对状态对象的引用
- c++ - 为什么我需要显式分离短期变量?
- symfony - EasyAdmin 捆绑包 - Symfony
- mongodb - 如何从流星中的mongo集合中检索数据?
- javascript - JavaScript 停留在从 HTML 访问样式元素
- python - 在 Python 中编写从 SPARQL 查询返回的 JSON 数据的正确方法
- python - heroku 上的 Django 应用程序:应用程序错误
- javascript - PrivateRouter 在 React JS 中不能正常工作