代码之家  ›  专栏  ›  技术社区  ›  Prince Ashitaka

在消息中检测到不匹配的组标记-protobuf net

  •  1
  • Prince Ashitaka  · 技术社区  · 15 年前

    我对Silverlight很陌生。我为一个主要依赖序列化和反序列化的项目工作。

    以前,对于WPF,我习惯于使用可序列化的类。对于silverlight,我发现protobuf会非常有用。但是,我为这个例外感到困扰。我不知道是什么导致了这个问题。请帮帮我。

    我正在使用Silverlight3.0。

    请找出我使用的代码。

    [ProtoContract]
    public class Report
    {
        public Report()
        {
        }
    
        [ProtoMember(1)]
        public SubReports SubReports { get; set; }
    }
    
    [ProtoContract]
    public class SubReports
       : List<SubReport>
    {
        public SubReports()
        {
        }
    
        [ProtoMember(1)]
        public SubReport SubReport { get; set; }
    }
    
    [ProtoContract]
    public class SubReport
    {
        public SubReport()
        {
        }
    
        [ProtoMember(1)]
        public string Name { get; set; }
    }
    

    我用来反序列化的代码是

        public static T Deserialize<T>(Byte[] bytes) where T
            : Report
        {
            return ProtoBuf.Serializer.Deserialize<T>(new MemoryStream(bytes));
        }
    

    我的示例XML类似于

    Report  
       ...SubReports  
          ...SubReport Name=”Q1 Report”   
          ...SubReport Name=”Q2 Report”   
          ...SubReport Name=”Q3 Report”   
          ...SubReport Name=”Q4 Report”     
    

    提前谢谢。
    维诺德

    1 回复  |  直到 15 年前
        1
  •  1
  •   Marc Gravell    15 年前

    (注意:我无法复制“组标签”问题;请参阅编辑历史,了解我对此的最初想法,现在已删除;如果你能帮我复制这个,我会很感激的)

    问题是 SubReports . 你已经定义了这个 二者都 [ProtoContract] ); 后者优先,所以它试图序列化 单一的 列表上的子报告(总是 null ?).

    如果将此更改为:

    // note no attributes, no child property
    public class SubReports : List<SubReport> { }
    

    Report.SubReports A. List<SubReport> 它应该很好用。以下工作:

    static void Main() {
        byte[] blob;
        // store a report
        using (MemoryStream ms = new MemoryStream()) {
            Report report = new Report {
                SubReports = new List<SubReport> {
                    new SubReport { Name="Q1"}, 
                    new SubReport { Name="Q2"},
                    new SubReport { Name="Q3"},
                    new SubReport { Name="Q4"},
                }
            };
    
            Serializer.Serialize(ms, report);
            blob = ms.ToArray();
        }
        // show the hex
        foreach (byte b in blob) { Console.Write(b.ToString("X2")); }
        Console.WriteLine();
    
        // reload it
        using (MemoryStream ms = new MemoryStream(blob)) {
            Report report = Serializer.Deserialize<Report>(ms);
            foreach (SubReport sub in report.SubReports) {
                Console.WriteLine(sub.Name);
            }
        }
    }
    

    显示blob:

    0A040A0251310A040A0251320A040A0251330A040A025134