The most common serialization is to serialize a class into a binary file, but sometimes we will serialize the class into an xml file.
For example
Class Arwen
{
Private Hashtable table = new Hashtable ();
Private TimeSpan time = new TimeSpan (0, 0, 1 );
Public Hashtable Table
{
Get {return table ;}
Set {table = value ;}
}
Public TimeSpan Time
{
Get {return time ;}
Set {time = value ;}
}
Public string Name {get; set ;}
}
If you serialize the Arwen class to binary, there is no problem at all. just add a [Serializable] in front of it. in addition, if a field or attribute is a class in the class, you must add [Serializable] before the class definition. if a field or attribute in the class does not want to be serialized, simply add [NonSerialized] before it. serialization to binary is equivalent to saving all information to binary files. private or public. no matter what type
Serialization into xml is much more restrictive than serialization into binary, mainly including three.
1 is a public field or attribute that can only be serialized. www.2cto.com
2. Some types cannot be serialized, such as the preceding Hastable and TimeSpan types.
3. constructor with or without parameters in the class can be serialized into xml.
What if you really want to save information of the Hastable and TimeSpan types?
That's the only way to save the country. convert the Hastable and Timespan to another type. it is serialized into xml and then converted when deserialization is returned. that also means you need to add a type to the original class. for example, a new pairs class has two fields corresponding to the Hastable key-value pair, and then stores all the information in Hastable using a List <pairs>. in this case, List <pairs> can be serialized. this is obviously a very troublesome and stupid method. but it seems that there is no better way. timeSpan can be converted to the string type first.
The following describes the simple usage of xml Conversion. As mentioned above, Hashtable and other types cannot be serialized. You can use a feature to explicitly declare them as not serializable. Use [XmlIgnoreAttribute ].
Using System. Xml. Serialization;
Using System. IO;
Class Arwen
{
Private Hashtable table = new Hashtable ();
Private TimeSpan time = new TimeSpan (0, 0, 1 );
Public Arwen ()
{
}
[XmlIgnoreAttribute]
Public Hashtable Table
{
Get {return table ;}
Set {table = value ;}
}
[XmlIgnoreAttribute]
Public TimeSpan Time
{
Get {return time ;}
Set {time = value ;}
}
}
Arwen weiwen = new Arwen ();
Weiwen. Time = new TimeSpan (1, 2, 3); // 1 hours, 2 minutes, 3 seconds
Weiwen. Table. Add ("arwen", 250 );
String filename = @ "c: \ temp \ arwen. xml ";
XmlSerializer xs = new XmlSerializer (typeof (Arwen ));
Using (FileStream file = new FileStream (filename, FileMode. Create ))
Xs. Serialize (file, sa );