关于C#结构体和byte[]之间的转换

1.转换成byte文件的形式:用来存储数据

[Serializable]

public class People
{
    public string Name { get; set; }
    public int Age { get; set; }
}//prefab 模式就是在mono里定义public的 People对象,把数据写进去,存成prefab。unity编辑器方便的查看修改序列化内容。
void Write(){//序列化写byte文件
FileStream fs = new FileStream("Asset\test.byte", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
List<People> ps = new List<People>();//也可以只new 一个对象
ps.Add(new People() { Name = "gg", Age = 24 });
ps.Add(new People() { Name = "yy", Age = 23 });
bf.Serialize(fs, ps);
fs.Close();
}
void Read(){//读byte文件
FileStream fs = new FileStream("Asset\test.byte", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
List<People> ps = bf.Deserialize(fs) as List<People>;
debug.log(ps[0].name)
//http://www.cnblogs.com/ustcwhc/archive/2011/11/01/2232195.html

}



2.转换成byte[]数据流直接使用  用来发送数据

public static byte[] Serialize(object data) 
{ //结构体一定要声明[Serializable]
BinaryFormatter formatter = new BinaryFormatter(); 
MemoryStream rems = new MemoryStream(); 
formatter.Serialize(rems, data); 
return rems.GetBuffer(); 


/// <summary> 
/// 反序列化 
public static object Deserialize(byte[] data) 

BinaryFormatter formatter = new BinaryFormatter(); 
MemoryStream rems = new MemoryStream(data); 
data = null; 
return formatter.Deserialize(rems); 
}

void main(){

SDProtity data=Deserialize[bytes] as SDProtity 

}



事实证明序列化的东西只适合本地存储使用,不适合网络传输,因为传输过程会解包 会改变,最终得到的byte[]反序列化就会失败!


版权声明:本文为gy373499700原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。