Пример #1
0
        private object ConvertObject(object obj, PropertyInfo property)
        {
            if (property.PropertyType.BaseType == typeof(Enum))
            {
                return(Enum.Parse(property.PropertyType, obj.ToString()));
            }
            else if (property.CustomAttributes.Count() > 0 && property.GetCustomAttribute <ProtoSerializeAttribute>() != null)
            {
                return(Protobuf.Deserialize((byte[])obj, property.PropertyType));
            }
            else if (CustomDeserializationMethods.ContainsKey(property.PropertyType))
            {
                return(CustomDeserializationMethods[property.PropertyType].Invoke(null, new object[] { obj }));
            }
            else if (property.PropertyType.IsGenericType)
            {
                if (property.PropertyType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    var genericType = property.PropertyType.GetGenericArguments()[0];
                    var newList     = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(genericType));

                    var split = obj.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

                    foreach (var element in split)
                    {
                        newList.Add(Convert.ChangeType(element, genericType, CultureInfo.InvariantCulture));
                    }
                    return(newList);
                }
            }
            else if (property.PropertyType == typeof(bool))
            {
                return(Convert.ToBoolean(Convert.ToInt16(obj)));
            }
            try
            {
                return(Convert.ChangeType(obj, property.PropertyType, CultureInfo.InvariantCulture));
            }
            catch
            {
                string exception = string.Format("Unknown constructor for '{0}', ({1}).", property.PropertyType.Name, property.Name);
                throw new Exception(exception);
            }
        }
Пример #2
0
        public void ShouldSerializeAndDeserialize()
        {
            var message  = Create <CMessage>();
            var protobuf = new Protobuf(new[] { typeof(CMessage) });

            using var stream = new MemoryStream();
            protobuf.Serialize(stream, message, 3);

            stream.Seek(0, SeekOrigin.Begin);
            var result = (CMessage)protobuf.Deserialize(stream, fieldNumber =>
            {
                if (fieldNumber == 3)
                {
                    return(typeof(CMessage));
                }

                throw new InvalidOperationException();
            });

            Assert.Equal(message.Value, result.Value);
        }