开发者

Serialising my class is failing because of an eventhandler

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?


you can do this:

[field:NonSerialized]
public event EventHandler MyEvent;


You can make the event a field like this:

    [NonSerialized]
    private EventHandler _eventHandler;

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜