serialize HybridDictionary to byte[]
I wrote below code
HybridDictionary state = new HybridDictionary();
using (MemoryStream buffer = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(buffer , state);
_backup.Push(buffer .ToArray());
}
but I got error on formatter.serialize(st,state) as below :
" System.Runtime.Serialization.SerializationException was unhandled by user code Message="Type 'System.ComponentModel.ReflectPropertyDescriptor' in Assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b开发者_运维技巧77a5c561934e089' is not marked as serializable."
what does it mean ?
Add
[field:NonSerializedAttribute()]
public event MyEventHandler SomeEvent;
to your events. This will omit them from serialization.
You should avoid serializing the registered event handlers on your events (As you state in the comment to the previous answer your objects do have events). If one of the registered handlers would not be serializable, this whould throw and exception.
The idea stems from a Forum post on Sanity Free dot org.
Here's how I have implemented this:
/// <summary>
/// Occurs when a property value changes.
/// </summary>
/// <devdoc>Do not serialize this delegate, since we do not want to have
/// the event listener persisted.</devdoc>
[NonSerialized]
private PropertyChangedEventHandler _propertyChanged;
/// <summary>
/// Occurs when a property value changes.
/// </summary>
/// <remarks>Effectively, this is fired whenever the wrapped MapXtreme theme
/// of the AssociatedTheme property gets changed
/// via the MapXtreme API.</remarks>
/// <devdoc>The implementation using the public event and the private delegate is
/// to avoid serializing the (probably non-serializable) listeners to this event.
/// see http://www.sanity-free.org/113/csharp_binary_serialization_oddities.html
/// for more information.
/// </devdoc>
public event PropertyChangedEventHandler PropertyChanged
{
[MethodImpl(MethodImplOptions.Synchronized)]
add
{
_propertyChanged = (PropertyChangedEventHandler)Delegate.Combine(_propertyChanged, value);
}
[MethodImpl(MethodImplOptions.Synchronized)]
remove
{
_propertyChanged = (PropertyChangedEventHandler)Delegate.Remove(_propertyChanged, value);
}
}
Best Regards, Marcel
Just as the error says, you have System.ComponentModel.ReflectPropertyDescriptor in your dictionary and it is not marked as serializable.
精彩评论