我只想反序列化某个数据成员,而不序列化它。
我知道我可以设置 EmitDefaultValue =false,并将值设置为 null。
但我也不想改变数据成员的值,有没有其他方法可以实现这一点?
序列化程序是 DataContractSerializer。 :)
谢谢。
最佳答案
您可以在序列化之前更改数据成员的值(更改为默认值,因此它不会被序列化),但是在序列化之后您可以将其改回 - 使用 [OnSerializing]
和 [OnSerialized]
回调(更多信息在 this blog post 中)。只要您没有多个线程同时序列化对象,这就可以正常工作。
public class StackOverflow_8010677
{
[DataContract(Name = "Person", Namespace = "")]
public class Person
{
[DataMember]
public string Name;
[DataMember(EmitDefaultValue = false)]
public int Age;
private int ageSaved;
[OnSerializing]
void OnSerializing(StreamingContext context)
{
this.ageSaved = this.Age;
this.Age = default(int); // will not be serialized
}
[OnSerialized]
void OnSerialized(StreamingContext context)
{
this.Age = this.ageSaved;
}
public override string ToString()
{
return string.Format("Person[Name={0},Age={1}]", this.Name, this.Age);
}
}
public static void Test()
{
Person p1 = new Person { Name = "Jane Roe", Age = 23 };
MemoryStream ms = new MemoryStream();
DataContractSerializer dcs = new DataContractSerializer(typeof(Person));
Console.WriteLine("Serializing: {0}", p1);
dcs.WriteObject(ms, p1);
Console.WriteLine(" ==> {0}", Encoding.UTF8.GetString(ms.ToArray()));
Console.WriteLine(" ==> After serialization: {0}", p1);
Console.WriteLine();
Console.WriteLine("Deserializing a XML which contains the Age member");
const string XML = "<Person><Age>33</Age><Name>John Doe</Name></Person>";
Person p2 = (Person)dcs.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(XML)));
Console.WriteLine(" ==> {0}", p2);
}
}
关于c# - 如何防止数据成员被序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8010677/