BinaryFormatter不能正常工作(Unity,C#)
创始人
2024-12-17 23:00:31
0

当使用Binary Formatter序列化对象时,应该注意以下几点:

  1. 被序列化的类必须标记为[Serializable],否则Binary Formatter将无法使用它。

  2. Binary Formatter只能序列化不包含引用特性的正常类,不能序列化静态类、接口、抽象类等特殊类。

  3. 序列化的类必须拥有无参数的构造函数,因为反序列化的过程需要创建实例,而无参构造函数是在反序列化过程中创建对象的基础。

下面是一些示例代码,演示了如何使用Binary Formatter序列化和反序列化对象:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class MyClass
{
    public int myInt;
    public string myString;

    public MyClass()
    {
        myInt = 0;
        myString = "";
    }
}

public class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();
        myClass.myInt = 42;
        myClass.myString = "Hello World!";

        // 序列化对象
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();
        formatter.Serialize(stream, myClass);

        // 将序列化后的数据保存到文件中
        using (FileStream file = new FileStream("data.bin", FileMode.Create, FileAccess.Write))
        {
            byte[] data = stream.ToArray();
            file.Write(data, 0, data.Length);
        }

        // 从文件中读取序列化后的数据,并反序列化成对象
        byte[] buffer;
        using (FileStream file = new FileStream("data.bin", FileMode.Open, FileAccess.Read))
        {
            buffer = new byte[file.Length];
            file.Read(buffer, 0, buffer.Length);
        }
        MemoryStream stream2 = new MemoryStream(buffer);
        MyClass myDeserializedClass = formatter.Deserialize(stream2) as MyClass;
    }
}

相关内容

热门资讯

二分钟发现!决战卡五星游戏辅助... 二分钟发现!决战卡五星游戏辅助器,poker world竟然真的是有挂,解密教程(有挂秘笈)1、决战...
必备攻略!旺旺福建麻将小程序麻... 必备攻略!旺旺福建麻将小程序麻将插件(透明挂)原来有挂(2024已更新)(哔哩哔哩);1、实时旺旺福...
微扑克有辅助挂!微扑克系统的发... 微扑克有辅助挂!微扑克系统的发牌速度有多快,微扑克有规律,玩家教程(有挂技巧);微扑克辅助插件是一个...
微扑克教程!wepoke算法(... 微扑克教程!wepoke算法(wepoke黑科技)WepokE(一直真的有挂);科技详细教程小薇《7...
9分钟科普!丽水都莱辅助器,A... 9分钟科普!丽水都莱辅助器,AApOKER切实有挂,2025新版总结(有挂神器)1、在丽水都莱辅助器...
重要通知!财神十三张开挂(透明... 重要通知!财神十三张开挂(透明挂)确实真的有挂(2023已更新)(哔哩哔哩)1、许多玩家不知道财神十...
微扑克辅助挂!微扑克系统发牌,... 1、微扑克辅助挂!微扑克系统发牌,WPK真是是有挂,专业教程(有挂解说)2、进入游戏-大厅左侧-新手...
wepower辅助器!wepo... 1、wepower辅助器!wepoke有软件(透明挂)wepOke(果真真的有挂);详细教程。2、w...
一分钟辅助!广西跑胡子有挂吗,... 一分钟辅助!广西跑胡子有挂吗,WEpoke其实是真的有挂,揭秘教程(有挂黑科技)1、广西跑胡子有挂吗...
一分钟带你了解!开心联盟金花怎... 一分钟带你了解!开心联盟金花怎么赢得多(透视)一直是真的有挂(2022已更新)(哔哩哔哩)1、下载好...