使用Protobuf,用[IgnoreDataMember]标记属性是多余的吗?

时间:2014-07-15 13:36:46

标签: protobuf-net

使用protobuf-net,用[IgnoreDataMember]标记属性是多余的吗?或者这与没有任何属性相同。

1 个答案:

答案 0 :(得分:2)

似乎没有必要使用protobuf-net。 IgnoreDataMember对DataContractSerializer很有用,因为默认行为是编写所有公开可见的类型。在这种情况下,你必须选择退出。对于protobuf-net,你必须选择加入。

但它确实可以覆盖基类成员并忽略基类中包含的属性

using System;
using System.IO;
using System.Runtime.Serialization;
using ProtoBuf;

namespace ProtoBufTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var test1 = new Test1() {Value1 = 5, Value2 = 10};
            using (var ms = new MemoryStream())
            {
                Serializer.Serialize(ms, test1);
                ms.Position = 0;
                var t = Serializer.Deserialize<Test1>(ms);
                Console.WriteLine(string.Format("Value written without DataMember: {0}", test1.Value2 == t.Value2));
            }

            var test2 = new Test2() {Value1 = 5, Value2 = 10};
            using (var ms = new MemoryStream())
            {
                Serializer.Serialize(ms, test2);
                ms.Position = 0;
                var t = Serializer.Deserialize<Test2>(ms);
                Console.WriteLine(string.Format("Value written with IgnoreDataMember: {0}", test2.Value2 == t.Value2));
            }

            var test3 = new Test3() {Value1 = 5, Value2 = 10};
            using (var ms = new MemoryStream())
            {
                Serializer.Serialize(ms, test3);
                ms.Position = 0;
                var t = Serializer.Deserialize<Test3>(ms);
                Console.WriteLine(string.Format("Value written with DataMember: {0}", test3.Value2 == t.Value2));
            }

        var test4 = new Test4() { Value1 = 5, Value2 = 10 };
        using (var ms = new MemoryStream())
        {
            Serializer.Serialize(ms, test4);
            ms.Position = 0;
            var t = Serializer.Deserialize<Test4>(ms);
            Console.WriteLine(string.Format("Value written with IgnoreDataMember override: {0}", test4.Value2 == t.Value2));
        }

            Console.ReadLine();
        }
    }

    [DataContract]
    internal class Test1
    {
        [DataMember(Order = 1)]
        public int Value1 { get; set; }

        public int Value2 { get; set; }
    }

    [DataContract]
    internal class Test2
    {
        [DataMember(Order = 1)]
        public int Value1 { get; set; }

        [IgnoreDataMember]
        public int Value2 { get; set; }
    }

    [DataContract]
    [ProtoInclude(3, typeof(Test4))]
    internal class Test3
    {
        [DataMember(Order = 1)]
        public int Value1 { get; set; }

        [DataMember(Order = 2)]
        public int Value2 { get; set; }
    }

    [DataContract]
    internal class Test4 : Test3
    {
        [IgnoreDataMember]
        public new int Value2 { get; set; }
    }
}

输出:

没有DataMember写的值:False

使用IgnoreDataMember写的值:False

使用DataMember写的值:True

使用IgnoreDataMember覆盖写入的值:False