Hello everybody i`m new to c#. Can you help me with understanding custom XML serialization.
Here is my code
C# Copy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace ConsoleApplication3
{
public class ShoppingCartItem : ISerializable
{
public int productID;
public decimal price;
public int quantity;
[NonSerialized ]
public decimal total;
public ShoppingCartItem ():this (0 ,0 ,0 ) {}
public ShoppingCartItem (int productID, decimal price, int quantity )
{
this .price = price;
this .productID = productID;
this .quantity = quantity;
total = price * quantity;
}
protected ShoppingCartItem (SerializationInfo info, StreamingContext sc )
{
this .price = info.GetDecimal("Price" );
this .productID = info.GetInt32("Product ID" );
this .quantity = info.GetInt32("Quantity" );
}
public virtual void GetObjectData (SerializationInfo info, StreamingContext sc )
{
info.AddValue("Price" , price);
info.AddValue("Product ID" , productID);
info.AddValue("Quantity" , quantity);
}
[OnSerialized ]
public void Calc (StreamingContext sc )
{
total = price * quantity;
}
[OnDeserialized ]
public void Check (StreamingContext sc )
{
if ( total == 0 ) Calc(sc);
}
}
class Program
{
public static void Main ()
{
ShoppingCartItem s = new ShoppingCartItem(5510 , 1236 , 12 );
XmlSerializer xs = new XmlSerializer(typeof (ShoppingCartItem));
FileStream fs = new FileStream("new.xml" , FileMode.Create);
xs.Serialize(fs, s);
fs.Close();
}
}
}
After serialization new.xml contains
5510 1236 12 14832 Why tags are not that which i had specified and why total is serialized?
Thanks.
Jaish MathewsRank #225 · 11K reputationPosted Apr 1, 2010, 10:31 AM EDT
I have straight answer for your "total" filed serialization issue. Because if u don't need to serialize a field, why need to mention it as public?. It's behaving like that i.e accessibility factor will override your serialization settings. If you don't need to serialise a filed, 1st behaviour expecting is that filed should be private. I made you field like below and now "total" not serializing.
[NonSerialized]private decimal total;
Vladimir Nani29 reputationPosted Apr 1, 2010, 11:24 AM EDT
Why when i say
info.AddValue("Price", price);
i have
but not