有没有办法在 protobuf-net 中使用 IReadOnlyCollection<T>/IReadOnlyList<T>

Is there a way to use IReadOnlyCollection<T>/IReadOnlyList<T> with protobuf-net

我了解到,在使用集合时,protobuf-net 需要 GetEnumerator 进行序列化,需要 Add 的类型进行反序列化。

对于没有 Add 的类型,您可以在反序列化之前设置继承类型。例如,这适用于 IEnumerableList:

[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]
public class Sheep
{
    public IEnumerable<string> Children { get; set; }
    public Sheep()
    {
        Children = new List<string>();
    }
}

var dolly = RuntimeTypeModel.Default.DeepClone(new Sheep
{
    Children = new[]
    {
        "Bonnie",
        "Sally",
        "Rosie",
        "Lucy",
        "Darcy",
        "Cotton"
    }
});

但是,当我对 IReadOnlyCollection(或 IReadOnlyList)执行相同操作时:

[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]
public class Sheep
{
    public IReadOnlyCollection<string> Children { get; set; }
    public Sheep()
    {
        Children = new List<string>();
    }
}

我遇到异常:

Unable to resolve a suitable Add method for System.Collections.Generic.IReadOnlyCollection`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

那么,有没有办法让 protobuf-net 处理 IReadOnlyCollection/IReadOnlyList 的成员?


编辑:我已经在项目存储库中针对此功能打开了一个问题:Support IReadOnlyCollection/IReadOnlyList members

这里的主要问题是"merge"。对于非合并(或者基本上:启用列表替换),我们可能可以硬编码一个具体的类型和策略,但是,对于合并没有明显的事情要做。

目前这个场景没有魔法;任何解决方案都需要更改库。