无涯教程-C# - 序列化

75 阅读1分钟

在C#中,序列化是将对象转换为字节流以便将其保存到内存、文件或数据库的过程。序列化的反向过程称为反序列化。

序列化在远程应用程序内部使用。

C# serialization

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("e:\\sss.txt", FileMode.OpenOrCreate);
        BinaryFormatter formatter=new BinaryFormatter();
    </span><span class="typ">Student</span><span class="pln"> s </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Student</span><span class="pun">(</span><span class="lit">101</span><span class="pun">,</span><span class="pln"> </span><span class="str">"sonoo"</span><span class="pun">);</span><span class="pln">
    formatter</span><span class="pun">.</span><span class="typ">Serialize</span><span class="pun">(</span><span class="pln">stream</span><span class="pun">,</span><span class="pln"> s</span><span class="pun">);</span><span class="pln">

    stream</span><span class="pun">.</span><span class="typ">Close</span><span class="pun">();</span><span class="pln">
</span><span class="pun">}</span><span class="pln">

}

sss.txt:

  JConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Student rollnoname e sonoo

如您所见,序列化数据存储在文件中。要获取数据,您需要执行反序列化。

参考链接

www.learnfk.com/csharp/c-sh…