首页 > 解决方案 > 为什么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 只运行一次(因为我只有一个字典)。

谢谢。

标签: c#

解决方案


您通过调用来调用枚举器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))

推荐阅读