Protobuf-net运行时序列化

时间:2012-06-18 06:51:08

标签: protobuf-net

[ProtoContract]
public abstract class Animal
{
    [ProtoMember(1)]
    public abstract string Type { get; set; }
    [ProtoMember(2)]
    public string Name { get; set; }
    [ProtoMember(3)]
    public int Likeability { get; set; }
}

public class Cat : Animal
{
    public override string Type { get; set; }
    public int Friendliness { get; set; }

    public override string ToString()
    {
        return String.Format("Type : {0}, Name : {1}, Likeability : {2}, Friendliness : {3}", Type, Name, Likeability, Friendliness);
    }
}

用例即

var animal = new Cat() { Name = "Whiskers", Friendliness = 10 , Type = "cat", Likeability = 5};
var model = TypeModel.Create();
model[typeof(Animal)].AddSubType(4, typeof(Cat));
model[typeof(Cat)].AddField(1, "Friendliness");
var typeModel = model.Compile();

var memoryStream = new MemoryStream();
typeModel.Serialize(memoryStream, animal);

var deserializedCat = new Cat() { Name = "PusPus" };
memoryStream.Seek(0, SeekOrigin.Begin);
var deserializedCat1 = typeModel.Deserialize(memoryStream, deserializedCat, typeof(Cat));
Console.WriteLine("deserializedCat : hash : " + deserializedCat.GetHashCode() + "\n" + deserializedCat);
Console.WriteLine("deserializedCat1 : hash : " + deserializedCat1.GetHashCode() + "\n" + deserializedCat1);

以上用例是否适用于可重复使用的运行时序列化,或者是否应明确映射" Cat"无视动物"并且有点困惑w.r.t" ComplileInPlace"它与Compile有何不同?

1 个答案:

答案 0 :(得分:2)

在运行时的映射方面,这看起来很好。它是否按预期工作?你回猫了吗?以及AnimalCat成员?

Compile*方法的差异:

  • CompileInPlace()生成现有模型,以便将来对model.Serialize(...)的调用将使用序列化表单。通常这是自动的,无论何时第一次需要每种类型,但这允许它提前准备; “就地”方法还有额外的功能 - 它可以访问私人成员,它可以为小的性能调整做额外的堆栈技巧 - 但它并不是在所有平台上都可用
  • Compile(string,string)允许您将模型编译为单独的dll文件,该文件可以被引用并用于全静态序列化(即在运行时没有反射)
  • Compile()执行之类的,但创建了一个从模型构建的TypeModel实例,没有单独的dll文件

在大多数情况下,CompileInPlace()就是您所追求的 - 尽管您根本不需要做任何事情,因为它通常会在需要时自动编译