I am trying to derive a class from ObservableCollection and I need to run just a single line of code each and every time any instance of this class is deserialized. My thought was to do this:
[Serializable]
public class ObservableCollection2<T> : ObservableCollection<T>, ISerializable
{
public ObservableCollection2()
: base()
{ }
public ObservableCollection2(SerializationInfo info, StreamingContext context)
: base(info, context)
{
// Put additional code here.
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
}
But I don't have access to those base methods related to serialization. Am I forced to re-write all of the serialization manually?
From stackoverflow
-
You can use the
OnDeserializedAttribute
: "When applied to a method, specifies that the method is called immediately after deserialization of the object." Note that the method also needs to accept aStreamingContext
parameter:[Serializable] public class ObservableCollection2<T>: ObservableCollection<T> { [OnDeserialized()] internal void OnDeserializedMethod(StreamingContext context) { this.DateDeserialized = DateTime.Now; } }
Henk Holterman : Good answer but an example with a few lines wouldn't hurt.Jeff Sternal : @Henk - on the way!Ben McIntosh : Awesome! Thanks! (P.S. You should remove ISerializable)Jim Leonardo : You mean it's one-line easy? How dare they! I thought everything was supposed to be hard and arcane so that the people dumber than me couldn't even begin to write code. Obviously, if you make things easy, normal people might want to write code.
0 comments:
Post a Comment