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

别说谁变了你拦得住时间么 提交于 2019-12-10 16:30:39

问题


I gather that when working with collections protobuf-net needs GetEnumerator for serialization and a type with Add for the deserialization.

For types that don't have an Add you can set an inheriting type that does before deserialization. This works for example with IEnumerable and a List:

[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"
    }
});

However, when I do the same with IReadOnlyCollection (or IReadOnlyList):

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

I get an exception:

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]]

So, is there a way to make protobuf-net handle members of IReadOnlyCollection/IReadOnlyList?


EDIT: I've opened an issue for this feature on the project's repository: Support IReadOnlyCollection/IReadOnlyList members


回答1:


The main problem here is "merge". For non-merge (or basically: with list replacement enabled), we could probably hard-code a concrete type and strategy, however, there is no obvious thing to do for merge otherwise.

There is no magic for this scenario at the moment; any solution would require library changes.



来源:https://stackoverflow.com/questions/30557636/is-there-a-way-to-use-ireadonlycollectiont-ireadonlylistt-with-protobuf-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!