ProtoBuf.net序列化派生类时不包括基类属性

时间:2011-05-24 11:45:06

标签: c# .net class protobuf-net

使用最新的2.0 beta版ProtoBuf.net我试图序列化派生类(只是示例),我得到空文件。为什么基类属性没有序列化?

[ProtoContract]
[Serializable]
public class Web2PdfClient : Web2PdfEntity
{

}

[ProtoContract]
[Serializable]
public class Web2PdfEntity : EngineEntity
{

    [ProtoMember(1)]
    public string Title { get; set; }
    [ProtoMember(2)]
    public string CUrl { get; set; }
    [ProtoMember(3)]
    public string FileName { get; set; }

}


[ProtoContract]
[Serializable]
public class EngineEntity
{

    public bool Result { get; set; }
    public string ErrorMessage { get; set; }
    public bool IsMembershipActive { get; set; }
    public int ConversionTimeout { get; set; }
    public byte[] FileStorage { get; set; }
}

使用下面的代码序列化类时我得到空文件。

var Web2PDF = new Web2PdfClient
                          {                                
                              CUrl = "http://www.google.com",
                              FileName = "test.txt"
                          };
        using (var file = File.Create(@"C:\Users\Administrator\Projects\temp\test.bin"))
        {
            Serializer.Serialize(file, Web2PDF);

        }

1 个答案:

答案 0 :(得分:6)

实际上,我很惊讶没有抛出异常 - 我会调查!为了使其工作,基类型必须具有指示每个子类型的唯一方式。这可以通过属性指定,或者(在v2中)在运行时指定。例如:

[ProtoContract]
[Serializable]
public class Web2PdfClient : Web2PdfEntity
{

}

[ProtoContract]
[ProtoInclude(7, typeof(Web2PdfClient))]
[Serializable]
public class Web2PdfEntity : EngineEntity
{ ... }

7没有什么特别之处,除了它不应该与为该类型定义的任何其他成员发生冲突。可以定义多个子类型(使用不同的标签)。另请注意,protobuf-net不会查看[Serializable],因此除非您还使用BinaryFormatter(或类似),否则不需要它。

同样,EngineEntity应宣传预期的子类型,并应指明要序列化的成员(以及针对哪个标记)。

相关问题