简体   繁体   English

每当对类的任何实例进行反序列化时,如何在C#类定义中运行代码?

[英]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.

相关问题 如何使用 c# 在运行时创建类的新实例? - How can I create a new instance of a class at run time using c#? 我已经将XML文件反序列化为class.cs,如何在c#ViewModel中使用它 - I have deserialized my XML file into class.cs, how can I use it in c# ViewModel C#如何编写可在类实例上调用的类方法 - c# how to code a class method that can be called on the instance of the class 如何使用BsonClassMap更改MongoDB C#Driver类反序列化的方式? - How can I use BsonClassMap to change the way a MongoDB C# Driver class is deserialized? 如何设计Storage类,使其可容纳任何存储类型,同时每种存储类型只有一个实例? - How do I design the Storage class such that it accommodates any storage type and at the same time there is only one instance of each? 如何在C#的特定时间运行代码 - How can I run a code at a specific time in C# c# 如何自动为 class 的每个实例增加 id - c# how to increment id for each instance of class automatically C#类定义 - C# Class Definition 在创建类实例C#时运行函数 - Run function on creation of class instance C# 如何创建一个我可以使用的类的实例是c#中的多个位置 - How can I create an instance of a class that I can use is more than one place in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM