简体   繁体   English

如何序列化自定义 EventHandler

[英]How to serialize a custom EventHandler

Good morning,早上好,

I got a class DirObserver with a custom event:我有一个带有自定义事件的 class DirObserver:

public EventHandler<FileDetectedEventArgs> NewFileDetected;

I try to serialize this class in a other class with:我尝试将这个 class 序列化到另一个 class 中:

private XmlSerializer serializer = new XmlSerializer(typeof(List<DirObserver>));

But i get an exception: FileDetectedEventArgs cannot be serialized because it does not have a parameterless constructor.但我得到一个例外: FileDetectedEventArgs 无法序列化,因为它没有无参数构造函数。

But the FileDetectedEventArgs-Class have a parameterless constructor:但是 FileDetectedEventArgs-Class 有一个无参数的构造函数:

public class FileDetectedEventArgs : EventArgs
{
    public String Source { get; set; }
    public String Destination { get; set; }
    public String FullName { get; set; }

    public FileDetectedEventArgs(String source, String destination, String fullName)
    {
        this.Source = source;
        this.Destination = destination;
        this.FullName = fullName;
    }

    public FileDetectedEventArgs() { }
} 

Nevertheless the exception will be raised.尽管如此,还是会引发异常。 Whats the problem here?这里有什么问题?

Thanks and greets Thomas感谢并问候托马斯

Change改变

public EventHandler<FileDetectedEventArgs> NewFileDetected;

to

public event EventHandler<FileDetectedEventArgs> NewFileDetected;

Eventhandlers are not made to be serialized.事件处理程序不是用来序列化的。 If you look into the inner exceptions of your exception, you will see it is the EventHandler class which does not have a parameterless constructor;如果查看异常的内部异常,您会发现它是 EventHandler class,它没有无参数构造函数; it is a delegate.它是一个代表。

You probably want to exclude the eventhandler from serialization;您可能希望从序列化中排除事件处理程序; add an XmlIgnore attribute.添加 XmlIgnore 属性。

Update更新

I missed the missing event keyword as mentioned by @Reniuz.我错过了@Reniuz 提到的丢失的事件关键字。 Serialization works with that correction.序列化适用于该更正。 Still, serializing eventhandlers in general is a bad idea I think.尽管如此,我认为一般来说序列化事件处理程序是一个坏主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM