2014-07-24 222 views
4

繼承我有這種模式:protobuf網不序列化泛型類型的泛型類型

[ProtoContract] 
[ProtoInclude(2, typeof(TestRequest<>))] 
public class XClass<T> 
{ 
    public XClass() 
    { 
    } 

    [ProtoMember(1)] 
    public T Value { get; set; } 
} 

[ProtoContract] 
public class TestRequest<T>: XClass<T> where T : ConcreteClass 
{ 

    public TestRequest() 
    { 
    } 

} 

[ProtoContract] 
public class ConcreteClass 
{ 
    [ProtoMember(1)] 
    public string Name { get; set; } 
} 

如果我嘗試序列,並與protobuf網反序列化:

TestRequest<ConcreteClass> request = new TestRequest<ConcreteClass>(); 
request.Value = new ConcreteClass() { Name = "test" }; 
MemoryStream msTestString = new MemoryStream(); 
Serializer.Serialize(msTestString, request); 
msTestString.Position = 0; 
request = Serializer.Deserialize < TestRequest<ConcreteClass>>(msTestString); 

並在此之後如果我檢查request.Value,它是空的。

我在做什麼錯了?

+0

在嘗試反序列化之前,msTestString的價值是什麼? –

+0

[protobuf繼承?]的可能的重複?(http://stackoverflow.com/questions/4746678/protobuf-with-inheritance) –

+0

沒有重複。我只有問題,如果泛型類型從另一個泛型繼承。 –

回答

1

這是設計與protobuf網。數據如此快速和輕便的原因之一是它不擔心類型信息。不幸的是(這取決於你的觀點)完全排除了它的繼承。

看到protobuf with inheritance?更多信息

1

從protobuf網的角度來看,它是底漆,並準備接收開放式泛型類型TestRequest<>爲現場2 ...但是,從來都沒有存在的TestRequest<>:只關閉通用類型作爲實際對象存在,所以TestRequest<>對protobuf-net無用。

什麼會在某些情況下工作:

[ProtoContract] 
[ProtoInclude(2, typeof(TestRequest<Foo>))] 
[ProtoInclude(3, typeof(TestRequest<Bar>))] 
[ProtoInclude(4, typeof(TestRequest<Blap>))] 

但是,它可能不是泛型自己混這是一個好主意。

我懷疑你實際上想要的是:

[ProtoContract] 
[ProtoInclude(2, typeof(TestRequest<T>))] 
public class XClass<T> {} 
然而

,我不知道如果這甚至編譯,更不用說如果是你所追求的。實際上,我的觀點是,如果你被束縛在這種類型的結中,你可能是可能過分複雜化你的序列化模型 - 通常是試圖序列化你的主域模型的結果 - 也許是時候轉向更簡單,專用的模式。