Sometimes we want to save instances of classes so that we can use them later. An intuitive way is to StreamWriter the class into one line, separating each attribute with T, and then reading it with StreamReader.
But this is too much trouble, there are more lines of code, and you must know in advance the corresponding position in the property row. At this point, if you use class serialization to save the code is simple:
If you have a class, add the [Serializable] attribute on top of it, which means that the class can be serialized.
[Serializable]
| The code is as follows |
Copy Code |
public class People { public string Name { Get Set } public int Age {get; set;} } |
The following code is then used to serialize an instance of the class to a file
Serialization of
| The code is as follows |
Copy Code |
FileStream fs = new FileStream (@ "D:programcsharpngramtestngramtestserializepeople.dat", FileMode.Create); People p = new people () {Name = "Haocheng Wu", age = 24}; BinaryFormatter bf = new BinaryFormatter (); Bf. Serialize (FS, p); Fs. Close (); |
This allows you to save an instance of this class on the file above, and if you want to read it, you can use the
Deserialization
| The code is as follows |
Copy Code |
FS = new FileStream (@ "D:programcsharpngramtestngramtestserializepeople.dat", FileMode.Open); BinaryFormatter bf = new BinaryFormatter (); People p = bf. Deserialize (FS) as people; |
Using the same method, you can serialize the list of a class to a file completely
| The code is as follows |
Copy Code |
Serialization list FileStream fs = new FileStream (@ "D:programcsharpngramtestngramtestserializepeople.dat", FileMode.Create); BinaryFormatter bf = new BinaryFormatter (); list<people> PS = new list<people> (); Ps. ADD (New People () {Name = "Haocheng Wu", age = 24}); Ps. ADD (New People () {Name = "James Wu", age = 23}); Bf. Serialize (FS, PS); Fs. Close (); |
The same way to read them:
| The code is as follows |
Copy Code |
Deserialization list fs = new FileStream (@ "D:programcsharpngramtestngramtestserializepeople.dat", FileMode.Open); BinaryFormatter bf = new BinaryFormatter (); list<people> PS = bf. Deserialize (FS) as list<people>; |
Serialization can do a lot of things, here just two simple examples, it is easy to extrapolate.