【问题标题】:Why protobuf-net serializes without atrributes?为什么 protobuf-net 序列化没有属性?
【发布时间】:2015-09-10 23:28:45
【问题描述】:

示例如下:

class A
{
    public int x { get; private set; }

    public A(){}
    public A(int x)
    {
        this.x = x;
    }
}
class Program
{
    static void Main(string[] args)
    {
        A a = new A(1);
        A a1;
        using (FileStream fs = new FileStream("data", FileMode.Create, FileAccess.Write))
        {
            Serializer.Serialize(fs, a);
        }

        using (FileStream fs = new FileStream("data", FileMode.Open, FileAccess.Read))
        {
            a1 = Serializer.Deserialize<A>(fs);
        }
        Console.ReadLine();
    }  
}

A 类没有任何属性或契约,但 protobuf-net 不会抛出任何异常。为什么? 反序列化后 a1.x 包含 1.

目标框架是 4.5。 Protobuf-net 版本为 2.0.0.668,使用 nuget 安装。

【问题讨论】:

    标签: c# .net serialization protocol-buffers protobuf-net


    【解决方案1】:

    这是v2的一个特性,来自the webpage

    “v2”发布

    “v2”是对核心引擎的一次重大改造,以允许 更大的灵活性,并避免过度使用的一些问题 的泛型。它与您现有的数据线兼容,并且 旧 API 仍然存在。简单地说:图书馆更干净、更精简, 并且对于以后的开发更加通用。特别是 v2 允许:

    • 允许在更多平台上使用(iOS、WP7、Android 的 Mono、WinRT 等)
    • 如果您愿意,可以在没有属性的情况下使用
    • 允许预先生成序列化程序集,以在运行时移除所有反射
    • 一般来说:只是更多功能

    (强调我的)

    【讨论】:

    • 感谢您的回答,我错过了。请问可以提供一些细节吗?在什么情况下可以序列化没有属性的对象?如果不需要属性,如果我只想要一些属性,我该如何选择要序列化的属性?
    • 如果您不应用任何属性,这与将属性应用到所有公共属性并按照它们在文件中声明的顺序编号相同。如果您只想要其中一些,则必须明确使用属性上的属性来标记您想要的。
    • 任何没有属性的类都将应用ProtoBuf.Meta.RuntimeTypeModel.Default中设置的行为。
    • 我还注意到,在这种情况下,删除带有(!)参数的构造函数会导致在 Serialize 中引发异常。为什么?根据我对 protobuf-net 的了解,它处理无参数构造函数。
    • 是你删除的构造函数YourClass(SerializationInfo, StreamingContext)
    猜你喜欢
    • 2013-06-16
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 2012-11-04
    相关资源
    最近更新 更多