序列化中的[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;
}
}