CSharp基础 专题
专题目录
您的位置:csharp > CSharp基础 专题 > C#序列化
C#序列化
作者:--    发布时间:2019-11-20

在 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,里边有记录对象的相关信息。内容如下所示 -


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册