2011-11-18 81 views
2

有誰知道什麼是正確的方式來設置ProtoContract接口protobuf-net和C#的接口

我收到以下異常「一旦生成序列化程序,就不能更改該類型」僅使用屬性。使用

代碼:

[ProtoContract] 
    public class Lesson5TestClass2 : ILesson5TestInteface1 
    { 
     [ProtoMember(1)] 
     public string Name { get; set; } 
     [ProtoMember(2)] 
     public string Phone { get; set; } 
    } 

    [ProtoContract] 
    [ProtoInclude(1000, typeof(Lesson5TestClass2))] 
    public interface ILesson5TestInteface1 
    { 
     [ProtoMember(1)] 
     string Name { get; set; } 
     [ProtoMember(2)] 
     string Phone { get; set; } 
    } 

我能夠反序列化只有當我添加以下設置:

RuntimeTypeModel.Default.Add(typeof (ILesson5TestInteface1), true) 
     .AddSubType(50, typeof(Lesson5TestClass2)); 

我真的很想來配置這樣僅使用屬性。

我使用NuGet的protobuf-net r470。

順便說一句:這個例子來自一組「Lessons through tests」,展示瞭如何使用protobuf-net爲我的同事進行序列化。

感謝您的閱讀:)

+0

爲什麼你需要DTO接口? – jgauffin

+0

@jgauffin:我只是寫一些代碼來理解protobuf-net的功能。第5課是關於接口的。 :) – graffic

回答

1

有趣;是的,它看起來像是在那裏。但是,它確實工作時爲成員曝光,即

[ProtoContract] 
class Wrapper 
{ 
    [ProtoMember(1)] 
    public ILesson5TestInteface1 Content { get; set; } 
} 
static class Program 
{ 
    static void Main() 
    { 
     Wrapper obj = new Wrapper 
     { 
      Content = new Lesson5TestClass2() 
     }, clone; 
     using(var ms = new MemoryStream()) 
     { 
      Serializer.Serialize(ms, obj); 
      ms.Position = 0; 
      clone = Serializer.Deserialize<Wrapper>(ms); 
     } 
     // here clone.Content *is* a Lesson5TestClass2 instance 
    } 
} 

我將不得不看看,看看是什麼了接口支持作爲對象。

+0

是的,它似乎有一個根對象的問題,當你從來沒有使用解串器。我寫了兩個測試,一個使用包裝,一個沒有包裝。如果首先運行包裝的測試,那麼沒有包裝的測試會通過。但是如果沒有包裝的測試首先運行,那麼這兩個測試都會失敗。 :? – graffic

+0

@graffic最好的事情就是記錄一個bug,然後我會進行調查。非常好奇。 –

+0

好吧:)星期五晚上在這裏,所以也許你得等到星期一(無論如何我都會盡力)。同時......我會接受你的回答,正確地解決這個問題。 – graffic