zoukankan      html  css  js  c++  java
  • c# 对象的序列化


    //本程序演示了最简单的序列化 和反序列化 ,将对象存储到本地文件中 ,
    //对象序列化的另一个目的是网络传输信息
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Xml.Serialization;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Data;
    namespace 序列化_啊
    {

        class Program
        {
            static void Main(string[] args)
            {
                //创建文件a.dat
                FileStream f = new FileStream("a.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                //创建类的实例t
                test t = new test();
                //给属性赋值
                t.A = "hello";
                t.N = 5;

                //二进制序列化
                IFormatter format = new BinaryFormatter();
                format.Serialize(f, t);
                f.Close();

                //读取文件
                f = new FileStream("a.dat", FileMode.Open, FileAccess.Read);
                test m = (test)format.Deserialize(f);
                Console.WriteLine(m.A);
                Console.WriteLine(m.N);
                f.Close();
               
                Console.Read();
            }

           [Serializable]//可序列化标记
            class test
            {
                int n = 0;
                string a = null;
                [NonSerialized]//不可序列化标记
                int b = 10;
                public int N
                {
                    set
                    {
                        n = value;
                    }
                    get
                    {
                        return n;
                    }
                }
                public string A
                {
                    set
                    {
                        a = value;
                    }
                    get
                    {
                        return a;
                    }
                }
            }
        }
    }

    阅读全文
    类别:默认分类 查看评论


    作者:玄魂
    出处:http://www.cnblogs.com/xuanhun/
    原文链接:http://www.cnblogs.com/xuanhun/ 更多内容,请访问我的个人站点 对编程,安全感兴趣的,加qq群:hacking-1群:303242737,hacking-2群:147098303,nw.js,electron交流群 313717550。
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    关注我:关注玄魂的微信公众号

  • 相关阅读:
    Redis到底该如何利用?
    AutoMapper搬运工之自定义类型转换
    AutoMapper搬运工之初探AutoMapper
    【ELK】docker-compose搭建ELK单机环境
    [flowable工作流引擎]基本概念及术语
    shell遍历文件夹读取文件夹下的文件
    vector类的简单实现
    string类的实现
    接口安全认证
    C# lock private VS private static
  • 原文地址:https://www.cnblogs.com/xuanhun/p/1662362.html
Copyright © 2011-2022 走看看