C # Object serialization (3) by: 23:43:39 Source: Tao Internet
Using system; ................................................... // Import necessary namespaces Using system. runtime. serialization. formatters. Binary; Using system. runtime. serialization; Using system. IO; Namespace customserialize { Public partial class form1: Form { // Declare the string type variable to store the path confirmed by the user String FN; Public form1 () { Initializecomponent (); } Private void form1_load (Object sender, eventargs E) { // When the form is loaded, the following two groupbox container controls are unavailable This. groupbox2.enabled = false; This. groupbox3.enabled = false; } Private void pathbtn_click (Object sender, eventargs E) { // Obtain the text attribute value of pathtxt and assign it to the text attribute value of the FN variable and pathlabel. Fn = pathtxt. text; Pathlabel. Text = FN; // The following two groupbox container controls are available This. groupbox1.enabled = false; This. groupbox2.enabled = true; // 1st groupbox container controls are available This. groupbox3.enabled = true; } Private void serbtn_click (Object sender, eventargs E) { // Create a details Class Object dt Details dt = new details (); // Copy the content of two text boxes to the two attributes of DT DT. Name = nametxt. text; DT. Nickname = nicknametxt. text; // Create an matter interface reference from the binaryformatter Class Object Iformatter FMt = new binaryformatter (); // Create a stream type reference FS and pass FN as the path Parameter Stream FS = new filestream (FN, filemode. Create, fileaccess. Write, fileshare. None ); // Call the FMT serialize method and pass the FS and DT Parameters FMT. serialize (FS, DT ); // Close the FS object FS. Close (); // Output the success message MessageBox. Show ("serialized "); } Private void deserbtn_click (Object sender, eventargs E) { Try { // Create a filestream type to reference FS and pass FN as the path parameter. The file mode is to open the file. Filestream FS = new filestream (FN, filemode. Open ); // Create a binaryformatter Class Object FMT Iformatter FMt = new binaryformatter (); // Call the deserialize method of the FMT object to pass the FS // Convert the objects in the fs stream to the details type and assign the reference value to DT Details dt = (details) FMT. deserialize (FS ); // Assign the DT attribute value to the text attribute values of the following two controls: Nametxtnew. Text = DT. Name; Nicknametxtnew. Text = DT. Nickname; } // Capture and display file not found exception Catch (filenotfoundexception ex) { String STR = string. Format ("exception message: {0}", Ex. Message ); MessageBox. Show (STR ); } } } [Serializable] // Define the details class to implement the iserializable Interface Public class details: iserializable { String _ name; String _ nickname; // Define two public attributes to read and write the corresponding private fields Public string name { Get { Return _ name; } Set { _ Name = value; } } Public String nickname { Get { Return _ nickname; } Set { _ Nickname = value; } } Public details (){} // Reload the constructor to receive two parameters Private details (serializationinfo inputinfo, streamingcontext SC) { Int I; // Obtain the value of "person name" and assign it to the _ name field. _ Name = inputinfo. getstring ("person name "); // Obtain the '>' character index value and the integer of 1 in the _ name field. I = _ name. indexof ('>') + 1; // Intercept the string content starting with index I and assign it to the _ name field _ Name = _ name. substring (I ); // Obtain the value of "person name" and assign it to the _ name field. _ Nickname = inputinfo. getstring ("person nickname "); // Obtain the '>' character index value and the integer of 1 in the _ name field. I = _ nickname. indexof ('>') + 1; // Intercept the string content starting with index I and assign it to the _ nickname Field _ Nickname = _ nickname. substring (I ); } // Implement the getobjectdata method of the iserializable interface and receive two parameters Void iserializable. getobjectdata (serializationinfo outputinfo, streamingcontext SC) { // Modify the value of the field to be serialized, modify the name, and fill in the outputinfo object Outputinfo. addvalue ("person name", "the boy's name is -->" + _ name ); Outputinfo. addvalue ("person nickname", "the boy's nickname is -->" + _ nickname ); } } } |
After the program runs, most widgets of the form are unavailable except those in the groupbox container control whose text attribute is "file path. Enter the file name to the text box control of the container (that is, the path is the current directory of the Assembly). Result 7.54 is displayed. After you click the "Confirm path" button, other controls in the form are available, and the controls in the container whose text attribute is "file path" become unavailable. In the text box control of the container whose text attribute is "raw Object Data", enter two string values and click "serialization". The result is 7.55.
| |
| (Click to view the larger image) Figure 7.54 input file path |
| |
| (Click to view the big image) Figure 7.55 to complete serialization |
First, the program creates a details Class Object and initializes the object according to the input value. Then, serialize the object, automatically call the getobjectdata () method implemented in the details class, modify the field value, and specify the corresponding key value. The boyname. dat file has been created in the directory where the Assembly is located. Open the "boyname. dat" file in Visual Studio 2005/Visual Studio 2008, as shown in Figure 7.56.
| |
| (Click to view the larger image) Figure 7.56 "boyname. dat" File Content |
As shown in figure 7.56, the field data of the original object is successfully modified, and "the boy's name is" is added before the _ name field value ", add "the boy's nickname is" before the _ nickname field value ". Second, the field name is not persistently stored in the DAT file, and the corresponding key values are changed to "person name" and "person nickname" respectively ". Finally, click "deserialization". Result 7.57 is displayed.
| |
| (Click to view the big chart) Figure 7.57 completes deserialization and outputs |
When a new object of the details class is created, its field data is consistent with that of the original object. This indicates that the operation of its overloaded constructor is successful. The modified part of the reload constructor of the details class is reversed to restore the data of the original object. Analysis In general, the serialization process details do not need to be taken into consideration. However, when developing a program, you must perform micro operations on the serialization process. You can use custom serialization to complete the process. Common Custom serialization methods enable using system when defining serializable types. runtime. serialization .. the iserializable interface. After this interface is implemented, the getobjectdata () method of this class is automatically called during the serialization of this class object. The microoperations required by developers can be defined in this getobjectdata () method. Correspondingly, you can also intervene in the deserialization process. deserialization re-creates objects of this Class Based on persistent data information. The class implementing the iserializable interface will use the overloaded constructor to create a new object. You can write the code that interferes with the deserialization process in this class of overloaded constructor, as shown in the following code:
Public class details: iserializable { Public details (){} // Reload the constructor to receive two parameters of the specified type Private details (serializationinfo inputinfo, streamingcontext SC) { Micro-operation code that interferes with the deserialization process; } // Implement the getobjectdata method of the iserializable interface and receive two parameters Void iserializable. getobjectdata (serializationinfo outputinfo, streamingcontext SC) { // Modify the value of the field to be serialized and fill it with the outputinfo object Outputinfo. addvalue ("key name", the modified value of the serialized field ); } } |
In the preceding code, the overload constructor must receive parameters of the specified type. The getobjectdata () method of the implementation interface calls the addvalue () method of the outputinfo parameter, you can perform micro-operations on the data in the serialization process. This addvalue () method has multiple overloaded versions, which are used to modify field values. |