如何防止数据成员被序列化 [英] How can I prevent a datamember from being serialized

查看:104
本文介绍了如何防止数据成员被序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想对某个数据成员进行反序列化,而不对其进行序列化.

I only want only to de-serializing a certain data member, without serializing it.

我知道我可以设置 EmitDefaultValue = false,并将值设置为 null.

I understand I can set EmitDefaultValue =false, and set the value to null.

但我也不想改变数据成员的值,还有其他方法可以实现吗?

But I also do not want to change the value of the datamember, is there any other way of achieving this?

序列化程序是 DataContractSerializer.:)

The serializer is DataContractSerializer. :)

谢谢.

推荐答案

您可以在序列化之前更改数据成员的值(更改为默认值,因此不会被序列化),但是在序列化之后您将它改回来 - 使用 [OnSerializing][OnSerialized] 回调(更多信息在 这篇博文).只要您没有多个线程同时序列化对象,这就可以正常工作.

You can change the value of the data member before the serialization (to the default value, so it doesn't get serialized), but then after the serialization you'd change it back - using the [OnSerializing] and [OnSerialized] callbacks (more information in this blog post). This works fine as long as you don't have multiple threads serializing the object at the same time.

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

这篇关于如何防止数据成员被序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆