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 这个类来序列化 数据
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/214213.html原文链接:https://javaforall.net
