I am new to XML serialization and I have read that private
variables cannot be serialized until they are given under a public property. But while debugging after deserializing I am able to find the private variables also in the deserialized object. Can someone explain this? Here is my code:
class Program
{
static void Main(string[] ar开发者_JAVA技巧gs)
{
XmlSerializer xs = new XmlSerializer(typeof(Nokia));
Nokia n = new Nokia();
using (Stream s = new FileStream("XMLFile", FileMode.Create, FileAccess.Write, FileShare.None))
{
xs.Serialize(s, n);
}
XmlSerializer xs1 = new XmlSerializer(typeof(Nokia));
using (Stream ds = File.OpenRead("XMLFile"))
{
Nokia dn = (Nokia)xs1.Deserialize(ds);
}
}
}
public class Mobile
{
public int Height = 10;
private int weight = 20;
public Mobile() {}
}
public class Nokia : Mobile
{
public string Signal = "Poor";
public Nokia() {}
}
While debugging when I quick watch my object after deserialization I am able to find the variable weight
in the base. How is it possible? Or am I wrong somewhere else?
The private variables will still exist in the deserialized object, but their values will not be stored in the XML serialized version.
To demonstrate this, if you create an instance of your object, change the weight
value then serialize it to XML. If you deserialize it, the value of weight
in the deserialized object will be the default value, rather than the value set on the original object.
精彩评论