【发布时间】:2011-07-06 09:57:02
【问题描述】:
protobuf-net ver 2 中有一个简洁的选项,称为 [ProtoMember(2,AsReference=true)]。在大多数情况下,这是一个后续问题:
我开始怀疑无论何时发生序列化/反序列化,是否始终保持引用完整性。当您使用 AsReference 选项时,protobuf-net 是否已经这样做了?
为了说明的目的,我整理了一个基本的代码示例,然后想,“也许我需要从 ORM 世界中借鉴一些想法?”我应该实施身份映射吗?我是否应该以某种方式告诉 protobuf(通过委托?)改为解析对/来自外键值的引用。
我想听到的答案是,protobuf-net 可以通过某种方式保持跨程序集边界的引用完整性,即使类型看起来很像。
但是,为了以防万一,这里有一个替代顺序:
a => 1. 解析对主键 int 的引用,2. 序列化
b => 3. 反序列化,4. 将主键 int 解析为引用
注释/约束:
类是彼此的镜像,但会在每个程序集中重新编译。
无论对象何时序列化,对象图都需要相同。即 A.ref=B(序列化/反序列化)。 C.ref=B(序列化/反序列化)。
讨论示例:
using System;
using System.Collections.Generic;
using ProtoBuf;
namespace protobuf_question
{
class Program
{
static void Main(string[] args)
{
var a = new A() { key = 1 };
var b = new B() { A = a, key = 2 };
}
}
[ProtoContract]
public class A
{
[ProtoMember(1)]
public int key { get; set; }
}
[ProtoContract]
public class B
{
[ProtoMember(1)]
public int key { get; set; }
[ProtoMember(2,AsReference=true)]
public A A { get; set; } // a reference
}
[ProtoContract]
public class IdentityMap<T,TKey>
{
public static readonly IdentityMap<T,TKey> instance = new IdentityMap<T,TKey>(); // singleton
private Dictionary<string, T> identitySpace { get; set; }
public IEnumerable<string> GetIdentitySet (/* some criteria */)
{
// used for serializing with reference safety between assemblies.
throw new NotImplementedException();
}
public TKey GetKey(T reference)
{
// map object reference to identity map; return identity.
throw new KeyNotFoundException();
}
}
}
【问题讨论】:
标签: protobuf-net