Dam*_*ian 6 protocol-buffers protobuf-net
我现在用谷歌搜索了一下,但是无法确定protobuf-net或protobuf是否通常支持以下意义上的向前兼容性:
该对象的旧版本使用新字段反序列化该对象的新版本,但在将其序列化时保留该字段,因此该对象的新版本不会丢失该值.
这与protobuf有关吗?
非常感谢
是; 大多数protobuf实现都支持往返未知数据.因为你特意标记了protobuf-net - 如果你使用的是代码优先(即手工编写类,这在protobuf-net中很常见),那么你需要明确地提供对它的支持.最简单的方法是继承Extensible
.以下显示了通过对该字段一无所知的类型的成功往返:
using System;
using System.IO;
using ProtoBuf;
[ProtoContract]
class Foo
{
[ProtoMember(1)]
public int X { get;set; }
[ProtoMember(2)]
public int Y { get;set; }
}
[ProtoContract]
class Bar : Extensible
{
[ProtoMember(1)]
public int A { get;set; } // if declared, needs to be compatible
// note we don't have a declared field 2 here
}
static class Program
{
static void Main()
{
Foo orig = new Foo { X = 123, Y = 456 }, clone;
Bar bar;
using(var ms = new MemoryStream())
{
Serializer.Serialize(ms, orig);
ms.Position = 0;
bar = Serializer.Deserialize<Bar>(ms);
Console.WriteLine(bar.A); // 123 // query known data
int b = Extensible.GetValue<int>(bar, 2); // query unknown data
Console.WriteLine(b); // 456
}
using (var ms = new MemoryStream())
{
Serializer.Serialize(ms, bar);
ms.Position = 0;
clone = Serializer.Deserialize<Foo>(ms);
}
Console.WriteLine(clone.X); // 123
Console.WriteLine(clone.Y); // 456
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
222 次 |
最近记录: |