使用 protobuf-net,用 [IgnoreDataMember]
标记属性是否多余?或者这与根本没有属性相同。
最佳答案
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
关于protobuf-net - 使用 Protobuf,用 [IgnoreDataMember] 标记属性是否多余?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24759734/