public void Serialize(Object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } var memberInfos = value.GetType().GetProperties().Where(p => Attribute.IsDefined(p, typeof(MessageMemberAttribute))).Select(p => MessageMemberInfo.FromPropertyInfo(p, value)); foreach (var m in memberInfos.OrderBy(x => x.MessageMemberAttribute.Index)) { if (m.Type == typeof(byte)) { WriteByte((byte)m.Value); } else if (m.Type == typeof(byte[])) { WriteBytes((byte[])m.Value); } else if (m.Type == typeof(short)) { WriteInt16((short)m.Value); } else if (m.Type == typeof(int)) { WriteInt32((int)m.Value); } else if (m.Type == typeof(ushort)) { WriteUInt16((ushort)m.Value); } else if (m.Type == typeof(uint)) { WriteUInt32((uint)m.Value); } else if (m.Type == typeof(int[])) { WriteInt32Array((int[])m.Value); } else if (m.Type == typeof(bool)) { WriteBool((bool)m.Value); } else { Serialize(m.Value); } } }
public T Deserialize <T>() where T : new() { T obj = new T(); var memberInfos = obj.GetType().GetProperties().Where(p => Attribute.IsDefined(p, typeof(MessageMemberAttribute))).Select(p => MessageMemberInfo.FromPropertyInfo(p, obj)); foreach (var m in memberInfos.OrderBy(x => x.MessageMemberAttribute.Index)) { Object value = null; if (m.Type == typeof(byte)) { value = ReadByte(); } else if (m.Type == typeof(byte[])) { value = ReadBytes(m.MessageMemberAttribute.Size); } else if (m.Type == typeof(ushort)) { value = ReadUInt16(); } else if (m.Type == typeof(bool)) { value = ReadBool(); } else { throw new NotImplementedException(); } m.PropertyInfo.SetValue(obj, value); } return(obj); }