使用内部值类型的接口键入的多维IReadOnlyDictionary

时间:2013-08-19 17:15:27

标签: c# dictionary interface covariance contravariance

这有点难以理解,所以我将通过例子来解释。以下代码无法编译:

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

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

1 个答案:

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