2012-06-18 23 views
1
[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); 
    } 
} 

使用情況下即protobuf網運行序列

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); 

是上面的使用情況可重複使用的運行時間序列正確還是應該一個明確映射「貓」忽略「動物」,也有點糊塗了關於「ComplileInPlace」與Compile有什麼不同?

+0

對我來說看起來不錯,除了我不知道爲什麼你會同時使用舊的和新的方式標記屬性。我只是在我想要序列化的所有對象上使用ProtoContract和ProtoMember,還缺少Cat類的'[ProtoContract]'。不知道編譯到位。 – Joe

+1

@Joe我認爲這裏的重點是'Cat'不是事先已知的 –

回答

2

就運行時的映射而言,看起來很好。它是否按預期工作?即你有貓嗎?和AnimalCat成員?

差異在Compile*方法:

  • CompileInPlace()使得現有模式,使得未來model.Serialize(...)通話將使用序列化形式。通常情況下,無論如何,這是第一次需要每種類型,但這可以提前做好準備; 「就地」方法也有額外的功能 - 它可以訪問私人會員,並且可以爲小型性能調整做一些額外的技巧 - 但它不適用於所有平臺
  • Compile(string,string)允許您將模型編譯爲單獨的dll文件,可以參考和使用全靜態序列化(在運行時即無反射)
  • Compile()做了這一點,但創建一個從該機型內置一個TypeModel的實例,而無需單獨的dll文件

在大多數情況下,CompileInPlace()是你所追求的 - 雖然你根本不需要做任何事情,因爲它通常會在需要時自動編譯到位

+0

是的,它確實工作正常,只是想確定用例,w.r.t CompileInPlace僅在某些平臺上可用,哪些平臺支持? – kalki

+0

@kalki如果方法在那裏,它應該工作。例如,我不認爲1.1支持CompileInPlace(無DynamicMethod)。 –