将对象(即任何对象,如person,employee)转换为silverlight中的byte []

tah*_*ala 5 silverlight byte object

我有一个person对象,需要将其存储为byte []并再次检索该byte []并转换为person对象并且Silverary中不提供BinaryFormatter

Kei*_*ler 6

由于t0mm13b提到的命名空间不是Silverlight .NET引擎的一部分,因此正确的方法是使用此解决方法来利用数据协定序列化程序:

http://forums.silverlight.net/forums/t/23161.aspx

从链接:

string SerializeWithDCS(object obj)
{
    if (obj == null) throw new ArgumentNullException("obj");
    DataContractSerializer dcs = new DataContractSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    dcs.WriteObject(ms, obj);
    return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position);
}
Run Code Online (Sandbox Code Playgroud)


t0m*_*13b -1

使用序列化类通过 MemoryStream 将对象转换为字节

使用 System.Runtime.Serialization.Formatters.Binary;
使用 System.Runtime.Serialization;

....
byte[] bPersonInfo = null;
使用 (MemoryStream mStream = new MemoryStream())
{
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new BinaryFormatter();
     bf.Serialize(mStream, personInfo);
     bPersonInfo = mStream.ToArray();
}
....
// 对 bPersonInfo 执行您必须执行的操作,bPersonInfo 是一个字节数组...

// 将其转换回来
PersonInfo pInfo = null;
使用(MemoryStream mStream = new MemoryStream(bPersonInfo)){
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new BinaryFormatter();
     pInfo = (PersonInfo)bf.DeSerialize(mStream);
}
// 现在 pInfo 是一个 PersonInfo 对象。

希望这有帮助,最诚挚的问候,汤姆。

  • 谢谢 Tom,BinaryFormatter 在 SilverLIight 中不可用 (4认同)