我的所有自定义实体集合都有一个基类,它的一个简单版本是这样的:
[Serializable]
public class CollectionBase<T> : List<T> where T : IEntity
{
public bool IsDirty {get;}
public new void Add(T item)
{
this.SetDirty();
base.Add(item);
item.MadeDirty += new EventHandler(item_MadeDirty);
}
// Other standard list methods overridden here
...
public void SetDirty() { } // Mark the collection as dirty
private void item_MadeDirty(object sender, EventArgs e)
{
this.SetDirty();
}
}
集合位于 Session
中的序列化类中(即 session 中的 Customer 类具有 Order 实体的集合)。问题是我的实体基类的 MadeDirty 事件如下:
[field: NonSerialized()]
public event EventHandler MadeDirty;
不幸的是,我不能只删除事件的 NonSerialized
属性,因为这会在部署到我的应用程序服务器时导致 session 状态服务器出现问题。
有什么方法可以捕获 CollectionBase 上的反序列化完成事件,以便我可以遍历所有项目并重新分配 session 中的每个反序列化的 MadeDirty
事件?即
private void OnDeserialized(object sender, EventArgs e)
{
foreach (T item in this)
{
item.MadeDirty+= new EventHandler(item_MadeDirty);
}
}
但是,我无法想象这是第一次有人遇到这个问题,那么还有更好的选择吗?
最佳答案
是的,您可以添加带有 special attribute 的方法以及您类(class)的正确签名:
[OnDeserializedAttribute()]
private void RunThisMethod(StreamingContext context)
{
// post-serialize your class
}
关于c# - 是否存在 OnDeserialized 事件或类似事件以便我可以确定某个类已被反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2999085/