在 C# 中,序列化是將對象轉換為位元組流的過程,以便將其保存到記憶體,檔或資料庫。序列化的反向過程稱為反序列化。
序列化可在遠程應用程式的內部使用。
C# SerializableAttribute
要序列化對象,需要將SerializableAttribute
屬性應用在指定類型上。如果不將SerializableAttribute
屬性應用於類型,則在運行時會拋出SerializationException
異常。
C# 序列化示例
下麵看看 C# 中序列化的簡單例子,在這個示例中將序列化Student
類的對象。在這裏使用BinaryFormatter.Serialize(stream,reference)
方法來序列化對象。
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Student
{
int rollno;
string name;
public Student(int rollno, string name)
{
this.rollno = rollno;
this.name = name;
}
}
public class SerializeExample
{
public static void Main(string[] args)
{
FileStream stream = new FileStream("F:\\worksp\\csharp\\serialize.txt", FileMode.OpenOrCreate);
BinaryFormatter formatter = new BinaryFormatter();
Student s = new Student(1010, "Curry");
formatter.Serialize(stream, s);
stream.Close();
}
}
執行上面示例代碼後,應該可以在F:\worksp\csharp目錄看到創建了一個檔:serialize.txt,裏邊有記錄對象的相關資訊。內容如下所示 -
上一篇:
C# DirectoryInfo類
下一篇:
C#反序列化