We know that we can add the serializable attribute to serialize and deserialize objects. It is usually used to store and transmit objects. For example
[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;
}
}
But sometimes, we do not need to serialize all the members (it is a waste of storage space and increases the transmission pressure), so we can use
[Nonserialized] To identify attributes and methods. For example
[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;
}
}
If so, total will not be serialized, but will not be initialized during the deserialization process. But what if we want to get the result of total in the deserialization object? Then we need
The ideserializationcallback interface and implements the ideserializationcallback. ondeserialization method. For example
[Serializable]
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;
}
}