Serialising my class is failing because of an eventhandler

旧时模样 提交于 2019-12-25 11:56:20

问题


I wasn't expecting to come across this error. I imagine I'm doing something wrong somewhere else.

I have an MVVM application.

My model can serialise its self using a BinaryFormatter. This was working fine.

Today I added in an event handler to my model, and the viewmodel that contains the model subscribes to this event.

Now when I try and serialise the model I get an error because my viewmodel isn't serialisable (by design).

I am sure it's down to the subscription to the event, because I've removed the subscription (and only that) and serialisation works again.

I can't apply the [NonSerialized] attribute to the handler because it's not a field.

It there a way around this issue?


回答1:


you can do this:

[field:NonSerialized]
public event EventHandler MyEvent;



回答2:


You can make the event a field like this:

    [NonSerialized]
    private EventHandler _eventHandler;

    public event EventHandler MyEvent
    {
        add { _eventHandler += value; }
        remove { _eventHandler -= value; }
    }



回答3:


I don't know how useful this is, but...

...extending what Pieter mentioned, you can also have mutliple delegate handlers wrapped into the same event, so you could (theoretically) make your event, in effect, both serializable and non-serializable by doing something like this:

[NonSerialized]
private EventHandler _nonSerializableeventHandler;
private EventHandler _eventHandler;

public event EventHandler MyEvent
{
    add
    {
        if (value.Method.DeclaringType.IsSerializable)
            _eventHandler += value;
        else
            _nonSerializableeventHandler += value;
    }
    remove
    {
        {
            if (value.Method.DeclaringType.IsSerializable)
                _eventHandler -= value;
            else
                _nonSerializableeventHandler -= value;
        }
    }
} 


来源:https://stackoverflow.com/questions/3979680/serialising-my-class-is-failing-because-of-an-eventhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!