2012-01-16 45 views
2

我在嘗試使用protobuf序列化類層次結構時遇到了一些問題。繼承自抽象類的類未實現的屬性沒有得到正確的值。例如,當我嘗試測試以下層次...:如何用抽象類使用protobuf序列化層次結構

[ProtoContract] 
[ProtoInclude(11, typeof(Child))] 
[ProtoInclude(12, typeof(Nanny))] 
public abstract class Person 
{ 
    [ProtoMember(1)] 
    public string Name { get; set; } 
} 

[ProtoContract] 
public class Child : Person 
{ 
    public Child(){ } 
} 

[ProtoContract] 
public class Nanny : Person 
{ 
    public Nanny() 
    { 
     Tutors = new List<ITutor<Person, Person>>(); 
    } 

    [ProtoMember(1)] 
    public List<ITutor<Person, Person>> Tutors { get; set; } 
} 

[ProtoContract] 
[ProtoInclude(11, typeof(NannyTutorChild))] 
public interface ITutor<out T, out U> 
    where T : Person 
    where U : Person 
{ 
    [ProtoMember(1, AsReference = true, DynamicType = true)] 
    T TutoredBy { get; } 

    [ProtoMember(2, AsReference = true, DynamicType = true)] 
    U Tutored { get; } 
} 

[ProtoContract] 
public abstract class Tutor<T, U> : ITutor<T, U> 
    where T : Person 
    where U : Person 
{ 
    [ProtoMember(1, AsReference = true, DynamicType = true)] 
    public T TutoredBy { get; set; } 

    [ProtoMember(2, AsReference = true, DynamicType = true)] 
    public U Tutored { get; set; } 
} 

[ProtoContract] 
public abstract class NannyTutor<U> : Tutor<Nanny, U> 
    where U : Person 
{ 
} 

[ProtoContract] 
public class NannyTutorChild : NannyTutor<Child> 
{ 
} 

所有NannyTutorChild的反序列化istances被設置爲空,即使他們叫Serializer.DeepClone之前正確增值的()。我發現實現它的唯一方法是標記爲Tutor類中的屬性,並在NannyTutorChild中實現它們。

我知道這可能看起來愚蠢的層次,但在我們的實際項目中,我們有很多來自我們的「導師」 classm派生不同的類和所有的水平,以強制轉換或使用正確的方法:)

需要

有什麼想法?難道我做錯了什麼?

謝謝大家, Mat。

回答

2

目前不支持此方案; DynamicType和繼承的組合存在複雜性,我仍然需要解決;我會在我正在等待工作的隊列中向前邁進,但是:它今天不在。

+0

謝謝!我會實現使用抽象屬性:) 保持良好的工作! – 2012-01-16 23:17:42

+0

@VollmonD強調,帶繼承的DynamicType組合是關鍵問題,我認爲 – 2012-01-16 23:56:03