对象如何转换为byte[]?

yumanqing 2007-10-14 11:06:45
我用下面的代码可以将对象转换为byte[],可是对象数组怎么转换呢?

Class2 c=new Class2();
c.A="faf";
c.B="ffff";
c.C="测试";
BinaryFormatter bf=new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, c);
byte[] bb = ms.GetBuffer();

比如:Class2[] c=new Class[2];
那么这个c怎么转换成byte[]呢?用上面的方法不行?
对这点不太熟悉.谢谢!
...全文
223 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
gxpotato 2007-10-16
  • 打赏
  • 举报
回复
先toString,然后用System.Text.Encoding.UTF8.GetByte
yumanqing 2007-10-16
  • 打赏
  • 举报
回复
UP,谢谢,我试试
fengyupeng 2007-10-15
  • 打赏
  • 举报
回复
Encoding.utf8.getbytes(string c);绝对正确;
yumanqing 2007-10-15
  • 打赏
  • 举报
回复
up
北京的雾霾天 2007-10-15
  • 打赏
  • 举报
回复
例如:

[Serializable]
public class MyObject : ISerializable
{
public int n1;
public int n2;
public String str;

public MyObject()
{
}

protected MyObject(SerializationInfo info, StreamingContext context)
{
n1 = info.GetInt32("i");
n2 = info.GetInt32("j");
str = info.GetString("k");
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("i", n1);
info.AddValue("j", n2);
info.AddValue("k", str);
}
}
北京的雾霾天 2007-10-15
  • 打赏
  • 举报
回复
对象必需加[Serializable] 属性才能被序列化,必要的时候,必要时需继承一下ISerializable并实现其接口成员方法来实现对象的序列化,从而使用Byte数组来表示对象。
cxx1997 2007-10-15
  • 打赏
  • 举报
回复
序列化对象的方法:

public static byte[] Serialize(object aObject)
{
//序列化发送内容
MemoryStream aMemoryStream = new MemoryStream();
BinaryFormatter aBinaryFormatter = new BinaryFormatter();
aBinaryFormatter.Serialize(aMemoryStream, aObject);

return aMemoryStream.ToArray();
}
bbdsj007 2007-10-15
  • 打赏
  • 举报
回复
用序列化就能把对象转换为byte[]
hzg_1998 2007-10-14
  • 打赏
  • 举报
回复
是一样的
[Serializable]
class Class2
{
public string A;
public string B;
public string C;
}

BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
Class2[] cc = new Class2[2];
cc[0] = new Class2();
cc[0].A = "how";
cc[1] = new Class2();
cc[1].B = "are you";
bf.Serialize(ms, cc);
byte[] bb = ms.GetBuffer();

ms = new MemoryStream(bb);
cc=(Class2[])bf.Deserialize(ms);

110,531

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧