Sometimes we want to save the class instance for future use. An intuitive method is to write the class as one line, separate each attribute with \ t, and then read it with streamreader.
However, this is too troublesome. There are many lines of code, and you must know the corresponding position of the attribute in the row in advance. At this time, if the class serialization method is used for saving, the code is very simple:
If you have a class, you can add the [serializable] attribute to it, indicating that the class can be serialized.
[Serializable]public class People{ public string Name { get; set; } public int Age { get; set; }}
Use the following code to serialize the class instance to a file:
// Serialize filestream FS = new filestream (@ "D: \ Program \ CSHARP \ ngramtest \ serializepeople. dat ", filemode. create); People P = new people () {name = "haocheng Wu", age = 24}; binaryformatter BF = new binaryformatter (); BF. serialize (FS, P); FS. close ();
In this way, the above file will save the instance of this class. If you want to read it, you can use
// Deserialization FS = new filestream (@ "D: \ Program \ CSHARP \ ngramtest \ serializepeople. dat ", filemode. open); binaryformatter BF = new binaryformatter (); People P = BF. deserialize (FS) as people;
Using the same method, you can also serialize the list of a class to a file.
// Serialize listfilestream FS = new filestream (@ "D: \ Program \ CSHARP \ ngramtest \ serializepeople. 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 read method is the same:
// Deserialization listfs = new filestream (@ "D: \ Program \ CSHARP \ ngramtest \ serializepeople. dat ", filemode. open); binaryformatter BF = new binaryformatter (); List <people> PS = BF. deserialize (FS) as list <people>;
Serialization can do a lot of things. Here we just give two simple examples, so it is easy to put them apart.