gpt4 book ai didi

c# - 嵌套接口(interface) : Cast IDictionary> 到 IDictionary>?

转载 作者:行者123 更新时间:2023-11-30 19:45:31 26 4
gpt4 key购买 nike

我认为转换 IDictionary<TKey, IList<TValue>> 相当简单反对 IDictionary<TKey, IEnumerable<TValue>> , 但是

var val = (IDictionary<TKey, IEnumerable<TValue>>)Value;

抛出 System.InvalidCastException , 和

var val = Value as IDictionary<TKey, IEnumerable<TValue>>;

制造 val无效的。转换这个的正确方法是什么?

最佳答案

I would think it's fairly straightforward to cast an IDictionary<TKey, IList<TValue>> object to an IDictionary<TKey, IEnumerable<TValue>>

绝对不是。它不会是类型安全的。这是为什么不这样做的示例:

// This is fine...
IDictionary<string, IList<int>> dictionary = new Dictionary<string, IList<int>>();

// Suppose this were valid...
IDictionary<string, IEnumerable<int>> badDictionary = dictionary;

// LinkedList<T> doesn't implement IList<T>
badDictionary["foo"] = new LinkedList<int>();

// What should happen now?
IList<int> bang = dictionary["foo"];

如您所见,这会导致问题 - 我们会尝试获取 LinkedList<int>当我们期望所有值都实现时输出 IList<int> .泛型的要点是类型安全——那么你希望哪一行失败?第一行、第三行和第四行对我来说显然是有效的 - 所以第二行是唯一可能无法编译的行,它确实...

现在在一些情况下,它可以安全地完成。例如,您可以从 IEnumerable<string> 转换(在 C# 4 中)至 IEnumerable<object>因为IEnumerable<T>只使用 T在“输出”位置。

参见 MSDN了解更多详情。

编辑:澄清一下 - 使用现有键/值对的副本创建字典很容易,例如使用链接:

var copy = original.ToDictionary<TKey, IEnumerable<TValue>>(pair => pair.Key,
pair => pair.Value);

您只需要知道您现在有两个单独的词典。

关于c# - 嵌套接口(interface) : Cast IDictionary<TKey, IList<TValue>> 到 IDictionary<TKey, IEnumerable<TValue>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10399568/

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