问题
Can I deserialize an object in the Silverlight 3.0 runtime that was serialized using the full .NET 2.0 runtime using the BinaryFormatter? I am using the following code to serialize an object to a ByteArray which we write to a DB table:
MemoryStream serStream = new MemoryStream();
BinaryFormatter binFormatter = new BinaryFormatter();
binFormatter.Serialize(serStream, csMetric);
serStream.Position = 0;
return serStream.ToArray();
The Silverlight client then needs to retrieve this binary data from the DB (via a Web service call) and deserizlize the bytes back into an instance of the csMetric class.
Is this possible? If so, how is that done on the client given that the BinaryFormatter is not availble in the SL 3.0 runtime?
Thanks, jon
回答1:
Since you have to go through WCF, and thus the full .NET Framework, to get the data into Silverlight anyway I'd recommend deserializing the object on the server before sending it back to Silverlight. The Silverlight 3 WCF stack supports binary WCF encoding which should make the data transfer reasonably efficient.
回答2:
Jon,
Have you tried to deserialize the object using the DataContractSerializer? I have not tested this exact scenario, but this is how I would approach it:
the following is an extension method off of a byte array (byte[]):
pubilc static T Deserialize<T>(this byte[] yourSerializedByteArray)
{
T deserializedObject;
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
using(MemoryStream ms = new MemoryStream(yourSerializedByteArray))
{
deserializedObject = (T)serializer.ReadObject(ms);
}
return deserializedObject;
}
回答3:
Maybe one would like to try my SharpSerializer. It can serialize data to the both binary and xml format. It works on .NET Full, Compact und Silverlight.
回答4:
DataContractSerializer has a whole bunch of problems, I've created a binary serializer that removes some of them (at least for me!) It uses reflection and produces reasonably compact representations that can be sent to WCF services.
More info here.
来源:https://stackoverflow.com/questions/1289910/silverlight-3-0-binary-serialization-support