序列化中的[NonSerialized]字段 -转

我们知道我们可以添加Serializable属性来序列化和反序列化对象。它通常用来储存、传输对象。例如

复制代码
[Serializable]
class ShoppingCartItem
{
public int productId;
public decimal price;
public int quantity;
public decimal total;
public ShoppingCartItem(int _productID, decimal _price, int _quantity)
{
productId = _productID;
price = _price;
quantity = _quantity;
total = price * quantity;
}
}
复制代码

但是有时候,我们并不需要序列化所有的成员(经常动不动序列化所有的有点浪费存储空间和增加传输压力). 所以我们可以用

[NonSerialized]来标识属性、方法等。例如

复制代码
[Serializable]
class ShoppingCartItem
{
public int productId;
public decimal price;
public int quantity;
[NonSerialized]
public decimal total;
public ShoppingCartItem(int _productID, decimal _price, int _quantity)
{
productId = _productID;
price = _price;
quantity = _quantity;
total = price * quantity;
}
}
复制代码

如果是这样的话, total 将不会被序列化,当然在反序列化过程中也不会被初始化,但是假如我们要在反序列化对象中得到total的结果怎么办呢?那我们就需要

IDeserializationCallback接口并实现IDeserializationCallback.OnDeserialization方法。例如

复制代码
class ShoppingCartItem : IDeserializationCallback {
public int productId;
public decimal price;
public int quantity;
[NonSerialized] public decimal total;
public ShoppingCartItem(int _productID, decimal _price, int _quantity)
{
productId = _productID;
price = _price;
quantity = _quantity;
total = price * quantity;
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
// After deserialization, calculate the total
total = price * quantity;
}
}
复制代码

 

posted @ 2012-11-15 09:01  武沛齐  阅读(4455)  评论(0编辑  收藏  举报