【发布时间】:2020-10-10 11:11:19
【问题描述】:
我只是在弄乱 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
' 转换为 'System.Collections.Generic.Dictionary '
现在在我写这篇文章时,我已经明白我的逻辑有缺陷,foreach 的第一个参数不能是字典。
但是 C# 怎么知道这应该是 KeyValuePair 呢?也许我真的打算在那里写字典,并使 foreach 只运行一次(因为我只有一个字典)。
谢谢。
【问题讨论】:
-
foreach(Dictionary<string, int> dict in operatii(5, 6))当您循环访问List<int>- 其中的每个条目都不是List<int>。这是一个int。完全相同的原则适用于Dictionary。条目不是字典。它们是键值对。 -
Maybe I really meant to write Dictionary in there, and make the foreach run only once (because I only have one Dictionary).也许这是你的意图,但它不会起作用。循环不是那样工作的。如果我遍历一盒苹果,我将一个接一个地遍历苹果。我不能决定买一个盒子(而不是一个单独的苹果)。这没有意义,循环方式。 -
感谢两位的回答。
标签: c#