MemoryStream 的一些用法

The following code example shows how to read and write data using memory as a backing store.

基本读写数据

using System;
using System.IO;
using System.Text;
using UnityEngine;

public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        string str = "this is a test message!";
        UnicodeEncoding encoding = new UnicodeEncoding();
        byte[] first_str = encoding.GetBytes(str);
        using (MemoryStream m = new MemoryStream(100) )
        {
            m.Write(first_str, 0, first_str.Length);
            int count = (int)m.Length;
            Debug.Log(string.Format("Capacity = {0},Length = {1}, Position = {2}", m.Capacity, m.Length, m.Position));

            m.Seek(0, SeekOrigin.Begin);
            byte[] byteArray = new byte[count];
            m.Read(byteArray, 0, count);
            Debug.Log(count);
            int num = encoding.GetCharCount(byteArray, 0, count);
            Debug.Log(num);
            char[] charArray = new char[num];
            
            encoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0);
            string s;
            s = string.Join("", charArray);
            Debug.Log(s);

            for (int i = 0; i < charArray.Length; i++)
            {
                Debug.Log(charArray[i]);
            }
        }
    }
}

这种方法只能处理文本,那么要处理其他类等数据呢,下面再看看第二种方法

using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Student
{
    public string name;
    public int id;
    public Gender gender;
}
[Serializable]
public enum Gender
{
    male,
    female,
}

public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Student student = new Student();
        student.name = "zhangsan";
        student.id = 11;
        student.gender = Gender.female;
        using (MemoryStream m = new MemoryStream(100) )
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(m, student);
            m.Position = 0;
            object obj = binaryFormatter.Deserialize(m);
            Student ss = (Student)obj;
            Debug.Log(ss.name);
        }
     }
}

我们使用了BinaryFormatter 这个类来序列化 数据

[参考文件]
[1]: https://docs.microsoft.com/en-us/dotnet/api/system.io.memorystream?redirectedfrom=MSDN&view=netframework-4.8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值