MemoryStream 的一些用法

MemoryStream 的一些用法MemoryStream 的一些用法 Thefollowing 基本读写数据 Thefollowing

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 这个类来序列化 数据

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/214213.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 下午4:44
下一篇 2026年3月18日 下午4:44


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号