문제

This is a little tricky to put into words, so I'll explain by example. The following code does not compile:

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 error I get is:

The best overloaded method match for
    'ReadOnlyDictionary<string,IReadOnlyDictionary<Guid,int>>
        .ReadOnlyDictionary(IDictionary<string,IReadOnlyDictionary<System.Guid,int>>)'
has some invalid arguments

Yet if I declare target using a class instead of an interface for the inner values, it compiles:

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

Why can't I use an interface for the inner dictionary?

도움이 되었습니까?

해결책

You can cast the ReadOnlyDictionary to an 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))));

Or specify the interface type as a generic argument to 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))));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top