【问题标题】:How do you serialize/deserialize jagged/nested arrays with protobuf-net?如何使用 protobuf-net 序列化/反序列化锯齿状/嵌套数组?
【发布时间】:2013-04-23 16:28:56
【问题描述】:

在他对For which scenarios is protobuf-net not appropriate? Marc 的回答中提到:

没有中间类型的锯齿状数组/嵌套列表是不行的 - 你可以通过在中间引入一个中间类型来解决这个问题

我希望这表明有一种方法可以在不更改我的底层代码的情况下做到这一点,也许使用代理? 有没有人找到序列化/反序列化嵌套/锯齿状数组的好方法

【问题讨论】:

标签: c# protobuf-net


【解决方案1】:

目前,它需要(如消息所示)更改您的模型。然而,原则上这是图书馆完全可以在自己的想象中完成的事情——这只是我还没有编写/测试过的简单代码。所以这取决于你多久需要它......我可以看看它,但我不能保证任何特定的时间尺度。

【讨论】:

  • 谢谢,这是我目前正在进行的一个项目。我需要调查改变我试图序列化的结构的影响。如果 protobuf-net 支持 2d/锯齿状数组,那就太好了,但我现在应该可以解决它
  • 是的,这里也绝对需要:)
【解决方案2】:

一种解决方案可能是序列化中间类型,并使用 getter/setter 将其隐藏在其余代码中。 示例:

    List<double[]> _nestedArray ; // The nested array I would like to serialize.

    [ProtoMember(1)] 
    private List<ProtobufArray<double>> _nestedArrayForProtoBuf // Never used elsewhere
    {
        get 
        {
            if (_nestedArray == null)  //  ( _nestedArray == null || _nestedArray.Count == 0 )  if the default constructor instanciate it
                return null;
            return _nestedArray.Select(p => new ProtobufArray<double>(p)).ToList();
        }
        set 
        {
            _nestedArray = value.Select(p => p.MyArray).ToList();
        }
    }



[ProtoContract]
public class ProtobufArray<T>   // The intermediate type
{
    [ProtoMember(1)]
    public T[] MyArray;

    public ProtobufArray()
    { }
    public ProtobufArray(T[] array)
    {
        MyArray = array;
    }
}

【讨论】:

    猜你喜欢
    • 2021-01-20
    • 2019-04-21
    • 2021-07-16
    • 2020-04-04
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多