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;
                }
            }
        }
    }
}

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

posted @   玄魂  阅读(401)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示