Windows Phone 7 Serialization: Binary Serialization

转自:http://www.devdiv.com/forum.php?mod=viewthread&tid=56924&extra=page%3D1%26filter%3Dtypeid%26typeid%3D305%26typeid%3D305

[p=24, null, left]Many of you probably noticed that Windows Phone 7 does not support standard Binary Serialization (using BinaryFormatter from System.Runtime.Serialization namespace), like full version of .NET Framework does, so I have decided to create my own custom solution for Binary serializationand deserialization using BinaryWriter and BinaryReader classes. This post covers my solution partly.

[p=24, null, left]

Additional Information Adding a reference[p=24, null, left]Probably this step could be optional if you decide to modify my code, but currently my approach to Binary serialization requires System.Runtime.Serialization namespace to be added to project for creating a SampleData class described bellow. To add a reference right click the project name and choose Add Reference there. Select System.Runtime.Serialization namespace on .NET tab (check image bellow).

[p=24, null, left] 

Creating a sample classI am going to use almost the same class I’ve created for theDataContract Serialization tutorial. To allow properties to be serialized you have to apply DataMemberAttribute to them.

  1. public class SampleData
  2. {
  3.     [DataMember]
  4.     public string ContentText { get; set; }

  5.     [DataMember]
  6.     public List<int> SomeItems { get; set; }

  7.     public SampleData()
  8.     {
  9.         ContentText = "some text";
  10.         SomeItems = new List<int>() { 1, 2, 3 };
  11.     }
  12. }
复制代码
Creating CustomBinarySerializer class My goal was to make Binary serialization and deserialization look similar to DataContract and XML Serialization , meaning that the should be a constructor that accepts type as parameter and two methods WriteObject and ReadObject. For this reasons I have created CustomBinarySerializer class. Currently, this class handles onlystring and List<int> types (for my SampleData class described above). Feel free to add other handled types and, perhaps, modify this class by creatingextention methods for those types like described inthis article. Partly implemented version of CustomBinarySerializer looks like that (pay attention that this class serialize and deserialize only those properties that are marked withDataMemberAttribute):
  1. public class CustomBinarySerializer
  2. {

  3.     private List<PropertyInfo> serializableProperties = new List<PropertyInfo>();
  4.     private Type serializableObjectType;

  5.     public CustomBinarySerializer(Type objectType)
  6.     {
  7.         serializableObjectType = objectType;
  8.         serializableProperties = GetMarkedProperties(objectType);
  9.     }

  10.     private List<PropertyInfo> GetMarkedProperties(Type type)
  11.     {
  12.         return (from property in type.GetProperties()
  13.                 where property.GetCustomAttributes(true)
  14.                 .Where((x) => x is System.Runtime.Serialization.DataMemberAttribute).Count() > 0
  15.                 select property
  16.                 ).ToList();
  17.     }

  18.     #region Write

  19.     public void WriteObject(Stream stream, object graph)
  20.     {
  21.         if (stream == null || graph == null)
  22.             return;

  23.         BinaryWriter bw = new BinaryWriter(stream);

  24.         foreach (PropertyInfo pi in serializableProperties)
  25.         {
  26.             var value = pi.GetValue(graph, null);

  27.             if (pi.PropertyType == typeof(string))
  28.             {
  29.                 bw.Write(value as string ?? string.Empty);
  30.             }
  31.             else if (pi.PropertyType == typeof(List<int>))
  32.             {
  33.                 WriteIntegerList(bw, value as List<int>);
  34.             }
  35.         }
  36.     }

  37.     private void WriteIntegerList(BinaryWriter bw, List<int> list)
  38.     {
  39.         if (list == null || !list.Any())
  40.         {
  41.             bw.Write(0);
  42.         }
  43.         else
  44.         {
  45.             bw.Write(list.Count);
  46.             list.ForEach(x => bw.Write(x));
  47.         }
  48.     }

  49.     #endregion Write

  50.     #region Read

  51.     public object ReadObject(Stream stream)
  52.     {
  53.         if (stream == null)
  54.             return null;

  55.         BinaryReader br = new BinaryReader(stream);

  56.         object deserializedObject = Activator.CreateInstance(serializableObjectType);

  57.         foreach (PropertyInfo pi in serializableProperties)
  58.         {
  59.             if (pi.PropertyType == typeof(string))
  60.             {
  61.                 pi.SetValue(deserializedObject, br.ReadString(), null);
  62.             }
  63.             else if (pi.PropertyType == typeof(List<int>))
  64.             {
  65.                 pi.SetValue(deserializedObject, ReadIntegerList(br), null);
  66.             }
  67.         }
  68.         return deserializedObject;
  69.     }

  70.     private List<int> ReadIntegerList(BinaryReader br)
  71.     {
  72.         List<int> list = new List<int>();
  73.         int count = br.ReadInt32();

  74.         int index = count;
  75.         while(index > 0){
  76.             list.Add(br.ReadInt32());
  77.             index--;
  78.         }
  79.         return list;
  80.     }

  81.     #endregion Read

  82. }
复制代码

SerializationTo serialize an object you need to create an instance of CustomBinarySerializer class (passing a type of serialized object as an input parameter) and then write serialized data to a stream object using WriteObject method, that accepts stream and object for serialization.
  1. public static void Serialize(Stream streamObject, object objForSerialization)
  2. {
  3.     if (objForSerialization == null || streamObject == null)
  4.         return;

  5.     CustomBinarySerializer ser = new CustomBinarySerializer(objForSerialization.GetType());
  6.     ser.WriteObject(streamObject, objForSerialization);
  7. }
复制代码

DeserializationTo deserialize your object you need to create an instance of CustomBinarySerializer class again (based on a type of serialized object) and then read serialized data using ReadObject method, that accepts an instance of Stream class as parameter.
  1. public static object Deserialize(Stream streamObject, Type serializedObjectType)
  2. {
  3.     if (serializedObjectType == null || streamObject == null)
  4.         return null;

  5.     CustomBinarySerializer ser = new CustomBinarySerializer(serializedObjectType);
  6.     return ser.ReadObject(streamObject);
  7. }
复制代码

TestingYou can use method bellow to test Binary serialization and deserialization. SampleData object after deserialization should be exactly the same as the one before the serialization.
  1. public static void Test()
  2. {
  3.     // serialization
  4.     MemoryStream ms = new MemoryStream();
  5.     BinarySerializationHelper.Serialize(ms, new SampleData());

  6.     ms.Position = 0;

  7.     // deserialization
  8.     var sampleData = BinarySerializationHelper.Deserialize(ms, typeof(SampleData));
  9.     ms.Close();
  10. }
复制代码
Here is how serialized SampleData object looks like during the debug: 

 

内容概要:本文详细介绍了一种基于Simulink的表贴式永磁同步电机(SPMSM)有限控制集模型预测电流控制(FCS-MPCC)仿真系统。通过构建PMSM数学模型、坐标变换、MPC控制器、SVPWM调制等模块,实现了对电机定子电流的高精度跟踪控制,具备快速动态响应和低稳态误差的特点。文中提供了完整的仿真建模步骤、关键参数设置、核心MATLAB函数代码及仿真结果分析,涵盖转速、电流、转矩和三相电流波形,验证了MPC控制策略在动态性能、稳态精度和抗负载扰动方面的优越性,并提出了参数自整定、加权代价函数、模型预测转矩控制和弱磁扩速等优化方向。; 适合人群:自动化、电气工程及其相关专业本科生、研究生,以及从事电机控制算法研究与仿真的工程技术人员;具备一定的电机原理、自动控制理论和Simulink仿真基础者更佳; 使用场景及目标:①用于永磁同步电机模型预测控制的教学演示、课程设计或毕业设计项目;②作为电机先进控制算法(如MPC、MPTC)的仿真验证平台;③支撑科研中对控制性能优化(如动态响应、抗干扰能力)的研究需求; 阅读建议:建议读者结合Simulink环境动手搭建模型,深入理解各模块间的信号流向与控制逻辑,重点掌握预测模型构建、代价函数设计与开关状态选择机制,并可通过修改电机参数或控制策略进行拓展实验,以增强实践与创新能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值