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

本文关键字:IReadOnlyDictionary 接口 内部 类型 | 更新日期: 2023-09-27 18:28:23

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

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

然而,如果我使用一个类而不是内部值的接口来声明target,它会编译:

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

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

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

您可以将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))));
相关文章:
  • 没有找到相关文章