这有点难以理解,所以我将通过例子来解释。以下代码无法编译:
var data = new[] {
new {Item = "abc", Values = new[] {1,2,3}},
new {Item = "def", Values = new[] {1,2,3}}};
IReadOnlyDictionary<string, IReadOnlyDictionary<Guid, int>> target;
target = new ReadOnlyDictionary<string, IReadOnlyDictionary<Guid, int>>(
data.ToDictionary(
i => i.Item,
v => new ReadOnlyDictionary<Guid, int>(
v.Values.ToDictionary(
a => Guid.NewGuid(),
b => b))));
我得到的错误是:
The best overloaded method match for
'ReadOnlyDictionary<string,IReadOnlyDictionary<Guid,int>>
.ReadOnlyDictionary(IDictionary<string,IReadOnlyDictionary<System.Guid,int>>)'
has some invalid arguments
然而,如果我使用类而不是内部值的接口声明目标,它将编译:
IReadOnlyDictionary<string, ReadOnlyDictionary<Guid, int>> target;
target = new ReadOnlyDictionary<string, ReadOnlyDictionary<Guid, int>>(
data.ToDictionary(
i => i.Item,
v => new ReadOnlyDictionary<Guid, int>(
v.Values.ToDictionary(
a => Guid.NewGuid(),
b => b))));
为什么我不能使用内部字典的接口?
答案 0 :(得分:3)
您可以将ReadOnlyDictionary
转换为IReadOnlyDictionary
:
target = new ReadOnlyDictionary<string, IReadOnlyDictionary<Guid, int>>(
data.ToDictionary(
i => i.Item,
v => (IReadOnlyDictionary<Guid, int>)new ReadOnlyDictionary<Guid, int>(
v.Values.ToDictionary(
a => Guid.NewGuid(),
b => b))));
或者将接口类型指定为ToDictionary
的通用参数:
target = new ReadOnlyDictionary<string, IReadOnlyDictionary<Guid, int>>(
data.ToDictionary<string, IReadOnlyDictionary<Guid, int>>(
i => i.Item,
v => new ReadOnlyDictionary<Guid, int>(
v.Values.ToDictionary(
a => Guid.NewGuid(),
b => b))));