如何在 Windows Phone 7 中使用 BinaryFormatter。
我用这个using System.Runtime.Serialization.Formatters.Binary
在 service1.svc.cs 中,但我无法在 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 中给出错误。那么我该怎么办反序列化。我必须在此代码中进行哪些更改?
正如@driis提到的,你不能使用BinaryFormatter
在 Windows Phone 上。您可以使用二进制文件encoding在 WCF 端点中(即,其绑定是自定义绑定的端点BinaryMessageEncodingBindingElement
和HttpTransportBindingElement
),并且 WP7 将支持该功能。您只是不能在那里使用二进制格式化程序。
更新以下评论:
查看您的代码,不仅需要更改该代码 - 您还需要更改service代码,以 Silverlight 支持的格式序列化对象。您可以使用DataContractSerializer
,使用二进制读取器/写入器,或者您可以使用这两种情况都支持的另一个库。例如,下面的代码应该在桌面版本和 SL 版本中都有效:
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();
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)