【发布时间】:2016-05-20 08:08:56
【问题描述】:
我正在尝试向内部 Collection 对象提供 IReadOnly-references。
这在大多数情况下效果很好,但如果我想将包含集合的字典转换为包含 IReadOnlyCollection 的 IReadOnlyDictionary,则不会。
这里是一个代码示例:
var list = new List<int>();
IReadOnlyList<int> listReference = list; //works;
var dictionary = new Dictionary<int, int>();
IReadOnlyDictionary<int, int> dictionaryReference = dictionary; //works
var nestedList = new List<List<int>>();
IReadOnlyList<IReadOnlyList<int>> nestedReadOnlyListReference = nestedList; //works
var nestedDictionary = new Dictionary<int, List<int>>();
//IReadOnlyDictionary<int, IReadOnlyList<int>> nestedReadOnlyDictionaryReference = nestedDictionary; //does not work, can not implicitly convert
//current workaround
var nestedDictionaryReferenceHelper = new Dictionary<int, IReadOnlyList<int>>();
foreach (var kvpNestedDictionary in nestedDictionary)
{
nestedDictionaryReferenceHelper.Add(kvpNestedDictionary.Key, (IReadOnlyList<int>)kvpNestedDictionary.Value);
}
IReadOnlyDictionary<int, IReadOnlyList<int>> nestedReadOnlyDictionaryReference = nestedDictionaryReferenceHelper; //works, but is only a reference to the internal List, not to the dictionary itself
解决方法非常难看,因为它需要额外的内存,并且每次nestedDictionary 的值发生变化时都需要手动更新。
有没有简单的方法来转换这种嵌套字典?
【问题讨论】:
标签: c# dictionary collections .net-4.5 readonly