如何在 Windows Phone 7 中使用 BinaryFormatter [英] How to Use BinaryFormatter in windows phone 7
问题描述
如何在 Windows Phone 7 中使用 BinaryFormatter.
How can I use BinaryFormatter in Windows Phone 7.
我在 service1.svc.cs 中使用这个 using System.Runtime.Serialization.Formatters.Binary
但我不能在 windows phone 7 中使用这个参考.
I use this using System.Runtime.Serialization.Formatters.Binary
in service1.svc.cs but I can't use this Reference in windows phone 7.
有什么解决办法吗?
我的反序列化对象代码
public static T DeserializeObject<T>(byte[] xml)
{
BinaryFormatter xs = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream(xml);
return (T)xs.Deserialize(memoryStream);
}
BinaryFormatter 在 Windows Phone 7 中出现错误.那么我如何反序列化.我必须在此代码中进行哪些更改?
BinaryFormatter gives error in windows phone 7. So how can I Deserialize. What changes that I have to do in this code?
推荐答案
正如@driis 提到的,你不能在 Windows Phone 上使用 BinaryFormatter
.您可以在 WCF 端点(即,其绑定是与 BinaryMessageEncodingBindingElement
和 HttpTransportBindingElement
的自定义绑定的端点)中使用二进制 encoding,这将在 WP7 上得到支持.你只是不能在那里使用二进制格式化程序.
As @driis mentioned, you cannot use BinaryFormatter
on Windows Phone. You can use the binary encoding in a WCF endpoint (i.e., an endpoint whose binding is a custom binding with the BinaryMessageEncodingBindingElement
and the HttpTransportBindingElement
), and that will be supported on WP7. You just cannot use the binary formatter there.
更新以下评论:查看您的代码,不仅需要更改代码 - 您还需要更改服务代码,以便以 Silverlight 支持的格式序列化对象.您可以使用带有二进制读取器/写入器的 DataContractSerializer
,或者您可以使用在这两种情况下都支持的另一个库.例如,下面的代码应该适用于桌面和 SL 版本:
Update following comment:
Looking at your code, it's not only that code that needs to be changed - you need to change the service code as well, to serialize an object in a format which is supported in Silverlight. You can use the DataContractSerializer
, with a binary reader / writer, or you can use another library which is supported in both cases. For example, the code below should work in both desktop and SL versions:
public static T DeserializeObject<T>(byte[] xml)
{
using (MemoryStream memoryStream = new MemoryStream(xml))
{
using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(
memoryStream, XmlDictionaryReaderQuotas.Max))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
return (T)dcs.ReadObject(reader);
}
}
}
在服务器上:
public static byte[] SerializeObject<T>(T obj)
{
using (MemoryStream ms = new MemoryStream())
{
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(ms))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
dcs.WriteObject(writer, obj);
writer.Flush();
return ms.ToArray();
}
}
}
这篇关于如何在 Windows Phone 7 中使用 BinaryFormatter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!