通用词典 - 获得转换错误

Pau*_*els 7 c# generics dictionary

以下代码给出了一个错误:

        // GetDirectoryList() returns Dictionary<string, DirectoryInfo>
        Dictionary<string, DirectoryInfo> myDirectoryList = GetDirectoryList();

        // The following line gives a compile error
        foreach (Dictionary<string, DirectoryInfo> eachItem in myDirectoryList)
Run Code Online (Sandbox Code Playgroud)

它给出的错误如下:

Cannot convert type 'System.Collections.Generic.KeyValuePair<string,System.IO.DirectoryInfo>' to 'System.Collections.Generic.Dictionary<string,System.IO.DirectoryInfo>’
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么要尝试执行此转换?我可以不在这种类型的对象上使用foreach循环吗?

Han*_*son 16

它应该是:

foreach (KeyValuePair<string, DirectoryInfo> eachItem in myDirectoryList)
Run Code Online (Sandbox Code Playgroud)

字典不包含其他字典,它包含键和值对.


Jus*_*ner 6

Dictionary<string, DirectoryInfo>

器物

IEnumerable<KeyValuePair<string, DirectoryInfo>>

这意味着foreach循环在KeyValuePair<string, DirectoryInfo>对象上循环:

foreach(KeyValuePair<string, DirectoryInfo> kvp in myDirectoryList)
{
}
Run Code Online (Sandbox Code Playgroud)

这也是为什么任何IEnumerable扩展方法也将始终与KeyValuePair对象一起使用的原因:

// Get all key/value pairs where the key starts with C:\
myDirectoryList.Where(kvp => kvp.Key.StartsWith("C:\\"));
Run Code Online (Sandbox Code Playgroud)