gpt4 book ai didi

c# - 无法将 Dictionary> 转换为 IReadOnlyDictionary>

转载 作者:行者123 更新时间:2023-12-05 08:04:28 25 4
gpt4 key购买 nike

谁能解释一下这个问题?

Dictionary<string, List<string>> x
= new Dictionary<string, List<string>>();

IReadOnlyDictionary<string, IReadOnlyCollection<string>> y
= new Dictionary<string, IReadOnlyCollection<string>>();

y = x; // CS0266: Cannot implicitly convert type...

最佳答案

您可以像这样接近您的目标:

Dictionary<string, List<string>> x = new Dictionary<string, List<string>>()
{
{ "Foo", new List<string> {"A", "B", "C"} }
};

IReadOnlyDictionary<string, ReadOnlyCollection<string>> y =
new ReadOnlyDictionary<string, ReadOnlyCollection<string>>(x.ToDictionary(k => k.Key, v => new ReadOnlyCollection<string>(v.Value)));

IReadOnlyCollection<string> foo = y["Foo"];

请注意 ReadOnlyCollection<T>包装您的原始列表。它不复制元素。 ReadOnlyDictionary<TKey, TValue> 相同.

关于c# - 无法将 Dictionary<string, List<string>> 转换为 IReadOnlyDictionary<string, IReadOnlyCollection<string>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68714516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com