c# - 如何防止数据成员被序列化

标签 c# serialization

我只想反序列化某个数据成员,而不序列化它。

我知道我可以设置 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/

相关文章:

c# - XML 解析器,多根

c# - 如何确定是否安装/注册了 VFPOLEDB 提供程序?

c# - myInterface.GetGenericTypeDefinition() 不等于 myType,但 myInterface.GetGenericTypeDefinition().FullName 等于 myType.FullName

c++ - 如何为QXmlStreamWriter/Reader序列化QColor、QSize、QPoint

c++ - 如何在 C++ 中使用对象序列化保存和加载 std::string?

python - 将 YAML 反序列化回 Python 对象

java - java.io.File.createNewFile() 处的 IOException;

java - Jackson:仅序列化给定类的给定实例变量

c# - WPF ListView 中字符串开头的省略号

c# - 适用于小型项目的 IronPython 与 C#