本文介绍了DataContractSerializer的问题事件/委托场的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的WPF应用程序,我使用的DataContractSerializer 序列化对象。我观察到,它没有序列化已经得到了一个事件或委托声明的类型。请看下面的失败code:

  [Serializable接口]
公共抽象类的BaseClass
{
    公共字符串名称{;组; }

    公共事件PropertyChangedEventHandler的PropertyChanged;
}

公共类DerivedClass:BaseClass的
{
    公众诠释年龄{获得;组; }
}


类节目
{
    静态无效的主要(字串[] args)
    {
        DerivedClass derivedClass =新DerivedClass {名称=测试,年龄= 10};
        derivedClass.PropertyChanged + =(发件人,EventArgs)=> Console.WriteLine(你好);

        DataContractSerializer的序列化=新的DataContractSerializer(typeof运算(DerivedClass));
        使用(的FileStream流=新的FileStream(C:\\的test.txt,FileMode.Create,FileAccess.ReadWrite))
        {
            serializer.WriteObject(流derivedClass);
        }
    }
}
 

这将失败,消息

我尝试添加像属性[数据成员(IsRequired = FALSE)] 上的事件,表示它不应该被序列化,但是毫无效果。

当我删除从 [Serializable接口] 属性的BaseClass 一切工作。我很奇怪,为什么这种行为?它是安全的,以避免给 [Serializable接口] 属性?

.NET framework版本:3.5 SP1

解决方案

  [字段:非序列化]
公共事件PropertyChangedEventHandler的PropertyChanged;
 

这告诉的DataContractSerializer ,不要序列自动生成的 EventHandlerList 字段,此事件。被序列化的对象图。因此,连接到您的事件的任何对象实例将不被考虑的部分。

On my WPF application, I am using DataContractSerializer to serialize object. I observed that it fails to serialize the types that has got an event or delegate declaration. Consider the following failing code:

[Serializable]
public abstract class BaseClass
{
    public string Name { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class DerivedClass : BaseClass
{
    public int Age { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        DerivedClass derivedClass = new DerivedClass {Name = "Test", Age = 10};
        derivedClass.PropertyChanged += (sender, eventArgs) => Console.WriteLine("hello");

        DataContractSerializer serializer  = new DataContractSerializer(typeof(DerivedClass));
        using(FileStream stream = new FileStream("c:\\test.txt", FileMode.Create, FileAccess.ReadWrite))
        {
            serializer.WriteObject(stream, derivedClass);
        }
    }
}

This fails with message

I tried to add attributes like [DataMember(IsRequired = false)] on the event to indicate that it should not be serialized, but nothing worked.

Everything worked when I removed the [Serializable] attribute from the BaseClass. I am wondering why this behavior? Is it safe to avoid giving [Serializable] attribute?

.NET framework version : 3.5 SP1

解决方案
[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;

This tells the DataContractSerializer, "don't serialize the auto-generated EventHandlerList field for this event". Thus, any object instances attached to your event won't be considered part of the object graph being serialized.

这篇关于DataContractSerializer的问题事件/委托场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:17