Recommendation 55: Reduce serializable fields with custom features
An attribute (attribute) can declaratively add a comment to a target element in your code. The runtime can achieve the purpose of changing the runtime behavior of the target element by querying the metadata information in these managed blocks. There are 4 such features under the System.Runtime.Serialization namespace:
- Ondeserializedattribute, when applied to a method, specifies that the method is called immediately after the object is deserialized.
- Ondeserializingattribute, when applied to a method, specifies that this method is called when deserializing an object.
- Onserializedattribute, when applied to a method, specifies that the method is called immediately after the object is serialized.
- Onserializingattribute, when applied to a method, specifies that this method is called when serializing an object.
These features allow for more flexibility in handling serialization and deserialization. For example, we can take advantage of this to further reduce some serializable fields.
The person class consists of Chinesename, FirstName, LastName fields:
[Serializable] class person { publicstring FirstName; Public string LastName; Public string chinesename; }
We know that chinesename can actually be inferred from FirstName and LastName, so this means that chinesename does not need to be serialized. At this point, we can use the feature to provide a way to calculate the value of the Chinesename after serialization is complete:
classProgram {Static voidMain () {person liming =NewPerson () {FirstName ="Ming", LastName ="Li", Chinesename ="Li Ming" }; Binaryserializer.serializetofile (liming,@"C +","Person.txt"); Person Person= Binaryserializer.deserializefromfile<person> (@"C:\Person.txt"); Console.WriteLine (person. Chinesename); }} [Serializable]classPerson { Public stringFirstName; Public stringLastName; [NonSerialized] Public stringChinesename; [Ondeserializedattribute]voidonserialized (StreamingContext context) {Chinesename=string. Format ("{0} {1}", LastName, FirstName); } }
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; } } }
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 55: Reduce serializable fields with custom features