Serialization of C# programming basics
1. The meaning of serialization
Serialization is to process an object into a byte stream to store the object or transfer it to memory, database or file. Its main purpose is to save the state of an object so that it can be recreated when needed. The opposite process is called deserialization.
1.1 How serialization works
This figure shows the entire process of serialization.
Objects are serialized into streams. Streams pass not only data but also information about the object type, such as the object's version, culture, and assembly name. Through this stream, objects can be stored in a database, file, or in memory.
1.2 For serialization
Through serialization, developers can save the state of an object and recreate it when needed This object provides object storage and data exchange. Serialization also enables developers to do things like send objects to remote applications through Web services, pass objects from one domain to another, pass objects as XML strings across firewalls, or across applications. The program maintains security information or user-specific information.
1.3 Make the object serializable
To serialize the object, you need the object to be serialized and the sequence to be included. Stream of objects, and a Formatter. System.Runtime.Serialization contains classes required to serialize and deserialize objects.
Applying the SerializableAttribute attribute to a type indicates that instances of the type can be serialized. When trying to serialize, if the type does not have the SerializableAttribute attribute, a SerializationException will be thrown.
If you do not want the fields in your class to be serializable, apply the NonSerializedAttribute attribute. If a field of a serializable type contains a pointer, handle, or some other data structure that is specific to a particular environment and cannot be reconstructed in a meaningful way in a different environment, you may need to make the field non-serializable.
If the serialized class contains references to objects of other classes marked with the SerializableAttribute, these objects will also be serialized.
1.3.1 Binary serialization and XML serialization
You can use binary serialization or XML serialization. In binary serialization, all members are serialized (even those that are read-only), which can improve performance. XML serialization provides more readable code and greater flexibility in object sharing and use for interoperability.
1.3.2 Binary serialization
Binary serialization uses binary encoding to generate a streamlined serialization for storage Or socket based network streaming etc.
1.3.3 XML serialization
##XML serialization can also be used to serialize objects into an XML stream that conforms to the SOAP specification. . SOAP is an XML-based protocol designed specifically for transporting procedure calls using XML. Like regular XML serialization, attributes can be used to control the text-style SOAP messages generated by XML Web services.
1.3.5 Basic serialization and custom serialization
Serialization can be performed in two ways: Basic serialization and custom serialization. Basic serialization uses the .NET Framework to automatically serialize objects.
1.3.5.1 Basic serialization
The only requirement for basic serialization is that the object must apply the SerializableAttribute attribute.
#NonSerializedAttribute can be used to disable serialization of specific fields.
Versioning of objects may cause problems when using basic serialization, in which case custom serialization may be more appropriate. Basic serialization is the simplest way to perform serialization, but does not provide much control over the process.
1.3.5.2 Custom Serialization
In custom serialization, you can specify exactly which objects will be serialized and how the serialization is done. Classes must be marked with SerializableAttribute and implement the ISerializable interface.
If you want to deserialize the object in a custom way as well, you must use a custom constructor.
1.3.6 Designer Serialization
Designer serialization is a special form of serialization that involves the kind of object persistence typically associated with development tools. Designer serialization is the process of converting an object graph into a source file that can later be used to restore the object graph. Source files can contain code, markup, and even SQL table information. For more information, see Designer Serialization Overview.
2. Save object data through serialization
Although you can set the properties of an object to default values at design time, if the object is damaged, all values entered at runtime will be lost. will be lost. You can use serialization to persist object data between instances, enabling values to be stored and retrieved the next time the object is instantiated.
In this walkthrough, you will create a simple object and save the object's data to a file. The data will then be retrieved from this file when you recreate the object. Finally, you'll modify the code to persist the object using SOAP format.
2.1 Save the object using serialization
[Serializable] //将类标记为可序列化 public class Coupon : INotifyPropertyChanged { public decimal Amount { get; set; } public float InterestRate { get; set; } public int Term { get; set; } private string _name; public string Name { get { return _name; } set { _name = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Customer")); } } [field: NonSerialized()] //将可序列化的类中的某字段标记为不被序列化 public event PropertyChangedEventHandler PropertyChanged; public Coupon(decimal amount, float interestRate, int term, string name) { Amount = amount; InterestRate = interestRate; Term = term; _name = name; } } static void Main(string[] args) { const string fileName = @"demo1.txt"; var coupon = new Coupon(10000, 0.2f, 1, "反骨仔"); using (var stream = File.Create(fileName)) { var deserializer = new BinaryFormatter(); //二进制格式序列化器 deserializer.Serialize(stream, coupon); //序列化对象到文件中 } }
Now try deserialization to see if it is consistent with the value of the previous Coupon object.
static void Main(string[] args) { const string fileName = @"demo1.txt"; //var coupon = new Coupon(10000, 0.2f, 1, "反骨仔"); //判断该文件是否存在 if (!File.Exists(fileName)) { return; } using (var stream = File.OpenRead(fileName)) { var deserializer = new BinaryFormatter(); //二进制序列化器 var coupon = deserializer.Deserialize(stream) as Coupon; //反序列化 if (coupon == null) { return; } Console.WriteLine($"{nameof(Coupon)}:"); Console.WriteLine($" {nameof(coupon.Amount)}: {coupon.Amount}"); Console.WriteLine($" {nameof(coupon.InterestRate)}: {coupon.InterestRate}%"); Console.WriteLine($" {nameof(coupon.Term)}: {coupon.Term}"); Console.WriteLine($" {nameof(coupon.Name)}: {coupon.Name}"); } Console.Read(); }
2.2 Use SOAP format to save objects
static void Main(string[] args) { const string fileName = @"demo1.txt"; var coupon = new Coupon(10000, 0.2f, 1, "反骨仔"); using (var stream = File.Create(fileName)) { var deserializer = new SoapFormatter(); //Soap 格式化器 deserializer.Serialize(stream, coupon); //序列化 } }
Deserialization SoapFormatter can also be used
var deserializer = new SoapFormatter(); //Soap 格式化器 var coupon = deserializer.Deserialize(stream) as Coupon; //反序列化
[Note] This example stores data in binary or SOAP format files. These formats should not be used for sensitive data such as passwords or credit card information.
#【Note】The binary format is suitable for most Windows applications. But for a Web application or Web service, you may want to save the object to an XML file using SOAP format to make the object easy to share.
Similarly, objects can also be serialized and saved in XML files through XmlSerializer. We can choose the appropriate serializer according to our needs, and the operation is basically the same.
The above is the content of serialization based on C# programming. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.
