[英]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. 我试图从ObservableCollection派生一个类,并且每次每次反序列化此类的任何实例时,我都只需要运行一行代码。 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." 您可以使用
OnDeserializedAttribute
:“当应用于方法时,指定在对象反序列化之后立即调用该方法。” Note that the method also needs to accept a StreamingContext
parameter: 请注意,该方法还需要接受
StreamingContext
参数:
[Serializable]
public class ObservableCollection2<T>: ObservableCollection<T>
{
[OnDeserialized()]
internal void OnDeserializedMethod(StreamingContext context)
{
this.DateDeserialized = DateTime.Now;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.