简体   繁体   中英

How can I run code in a C# class definition each time any instance of the class is deserialized?

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?

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 a StreamingContext parameter:

[Serializable]
public class ObservableCollection2<T>: ObservableCollection<T>
{
    [OnDeserialized()]
    internal void OnDeserializedMethod(StreamingContext context)
    {
        this.DateDeserialized = DateTime.Now;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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