Recommendation 54: Labeling of useless fields is not serializable
Serialization refers to a technique that transforms an object into a stream. The reverse process, we call deserialization. This technique is needed on many occasions.
- Save the object locally and restore the object the next time you run the program.
- Upload the object to another terminal on the network, and then restore the object at this terminal.
- Other occasions, such as: Assign the object to the system's pasteboard, and then use the shortcut key Ctrl + V to restore the object.
For a couple of reasons, it's decided that you want to label non-serializable for a useless field:
- Save space. Types are often stored in a place after serialization, such as a database, hard disk, or memory, and if a field does not need to be persisted after deserialization, it should not be serialized, which consumes valuable space resources.
- The field information after deserialization is meaningless. such as the Windows kernel handle, after deserialization often has lost meaning, so it should not be serialized.
- The field is not allowed to be serialized for business reasons. For example, plaintext passwords should not be serialized and stored together in a file.
- If the type of the field itself is not set to serializable in the code, it should be labeled non-serializable, otherwise the runtime throws a SerializationException exception.
After the type is added to the serializable attribute, all fields of the default can be serialized. If a part of the field does not require serialization, you can apply the NonSerialized attribute on that field. Properties are actually methods, so they are not serializable, and so are automatic attributes. In addition, to identify events as non-serializable, you need to use the field:nonserialized syntax.
The following is a serialization tool class:
Public classBinaryserializer {//serializing a type to a string Public Static stringSerialize<t>(T t) {using(MemoryStream stream =NewMemoryStream ()) {BinaryFormatter Formatter=NewBinaryFormatter (); Formatter. Serialize (stream, T); returnSystem.Text.Encoding.UTF8.GetString (stream. ToArray ()); } } //serializing a type to a file Public Static voidSerializetofile<t> (T T,stringPathstringfullName) { if(!directory.exists (path)) {directory.createdirectory (path); } stringFullPath =Path.Combine (Path, fullName); using(FileStream stream =NewFileStream (FullPath, FileMode.OpenOrCreate)) {BinaryFormatter Formatter=NewBinaryFormatter (); Formatter. Serialize (stream, T); Stream. Flush (); } } //deserializing a string into a type Public StaticTResult deserialize<tresult> (stringSwhereTResult:class { byte[] bs =System.Text.Encoding.UTF8.GetBytes (s); using(MemoryStream stream =NewMemoryStream (BS)) {BinaryFormatter Formatter=NewBinaryFormatter (); returnFormatter. Deserialize (Stream) asTResult; } } //deserializing a file into a type Public StaticTResult deserializefromfile<tresult> (stringPathwhereTResult:class { using(FileStream stream =NewFileStream (path, FileMode.Open)) {BinaryFormatter Formatter=NewBinaryFormatter (); returnFormatter. Deserialize (Stream) asTResult; } } }
Instance code:
classProgram {Static voidMain () {person Mike=NewPerson () {age = +, Name ="Mike" }; Mike. Namechanged+=NewEventHandler (mike_namechanged); Binaryserializer.serializetofile (Mike,@"C +","Person.txt"); Person P= Binaryserializer.deserializefromfile<person> (@"C:\person.txt"); P.name="Rose"; Console.WriteLine (P.name); Console.WriteLine (P.age.tostring ()); } Static voidMike_namechanged (Objectsender, EventArgs e) {Console.WriteLine ("Name Changed"); }} [Serializable]classPerson {Private stringname; Public stringName {Get { returnname; } Set { if(Namechanged! =NULL) {namechanged ( This,NULL); } name=value; } } Public intAge {Get;Set; } [NonSerialized]PrivateDepartment Department; PublicDepartment Department {Get { returnDepartment; } Set{Department=value; }} [field:nonserialized] Public EventEventHandler namechanged; }
Output:
Rose
21st
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 54: label non-serializable for useless fields