且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Windows Phone 7 中使用 BinaryFormatter

更新时间:2023-01-24 15:33:24

正如@driis 提到的,你不能在 Windows Phone 上使用 BinaryFormatter.您可以在 WCF 端点(即,其绑定是与 BinaryMessageEncodingBindingElementHttpTransportBindingElement 的自定义绑定的端点)中使用二进制 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();
        }
    }
}