Почему KeyCollection keys = dict.Keys; дать ошибку времени компиляции? - PullRequest
0 голосов
/ 05 марта 2020

Предположим, у меня есть следующий словарь:

class MyType
{
     //... ...
}

Dictionary<string, MyType> dict;

Затем

KeyCollection keys = dict.Keys;

показывает ошибку времени компиляции.

Почему это так?

Ответы [ 2 ]

2 голосов
/ 05 марта 2020

Посмотрите на класс Dictionary (https://referencesource.microsoft.com/#mscorlib / system / collection / generic / dictionary.cs ). Вы увидите

public KeyCollection Keys { get; } // This gives you collection of string
public ValueCollection Values { get; } // This gives you collection of MyType

ОБНОВЛЕНО: чтобы показать вам, как его получить

    public static void Main(string[] args)
    {
        Dictionary<string, MyType> dict = new Dictionary<string, MyType>();
        Dictionary<string, MyType>.KeyCollection myKeys = dict.Keys;
    }
1 голос
/ 05 марта 2020
IEnumerable<string> keys = dict.Keys;
IEnumerable<MyType> values = dict.Values;
...