2

这有点难以用语言表达,所以我将通过示例进行解释。以下代码无法编译:

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))));

为什么我不能使用内部字典的接口?

4

1 回答 1

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))));
于 2013-08-19T17:16:57.090 回答