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

标签 c# .net class protobuf-net

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

[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);

        }

最佳答案

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

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

}

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

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

同样,EngineEntity 应该通告它的预期的子类型,并且应该指示要序列化的成员(以及针对哪个标记)。

关于c# - 序列化派生类时不包括 ProtoBuf.net 基类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6109868/

相关文章:

java - 增加一个整数的 int 值?

c# - 如何清除调试器输出窗口 Visual Studio 2012

c# - 由于回发而未存储变量

c# - 系统.Linq.表达式 : Binding LambdaExpression inputs at runtime

java - 为什么此构造函数中不需要 "this."命令? ( java )

javascript - 有没有比这更有效的方法来点击切换多个类?

c#获取CPU使用率高的进程

c# - 如何为 DevExpress WPF GridControl 行着色?

.net - 在更改对对象的引用时,Visual Basic 中的 WithEvents 是否保留其 EventHandlers?

c# - 按字符拆分字符串