convert object(i.e any object like person, employe

2020-06-18 09:52发布

i have a person object and need to store it as byte[] and again retrieve that byte[] and convert to person object and BinaryFormatter is not availabe in silverlight

5条回答
家丑人穷心不美
2楼-- · 2020-06-18 10:15

Use the serialized class to convert the object into a byte via using a MemoryStream

using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

....
byte[] bPersonInfo = null;
using (MemoryStream mStream = new MemoryStream())
{
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new BinaryFormatter();
     bf.Serialize(mStream, personInfo);
     bPersonInfo = mStream.ToArray();
}
....
// Do what you have to do with bPersonInfo which is a byte Array...

// To Convert it back
PersonInfo pInfo = null;
using (MemoryStream mStream = new MemoryStream(bPersonInfo)){
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new BinaryFormatter();
     pInfo = (PersonInfo)bf.DeSerialize(mStream);
}
// Now pInfo is a PersonInfo object.

Hope this helps, Best regards, Tom.

查看更多
▲ chillily
3楼-- · 2020-06-18 10:18

Because the namespaces mentioned by t0mm13b are not part of the Silverlight .NET engine, the correct way to is to use this workaround leveraging the data contract serializer:

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

From the link:

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);
}
查看更多
狗以群分
4楼-- · 2020-06-18 10:26

If you really need binary and want it to be super fast and very small, then you should use protobuf from Google.

http://code.google.com/p/protobuf-net/

Look at these performance numbers. Protobuf is far and away the fastest and smallest.

enter image description here

I've used it for WCF <--> Silverlight with success and would not hesitate to use it again for a new project.

查看更多
We Are One
5楼-- · 2020-06-18 10:29

Look at custom binary serialization and compression here

and here

查看更多
放荡不羁爱自由
6楼-- · 2020-06-18 10:31

I have used XML Serializer to convert the object to a string and them convert the string to byte[] successfully in Silverlight.

object address = new Address();

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Address));
            StringBuilder stringBuilder = new StringBuilder();
            using (StringWriter writer = new StringWriter(stringBuilder))
            {
                serializer.Serialize(writer, address);
            }

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] data = encoding.GetBytes(stringBuilder.ToString());
查看更多
登录 后发表回答