protected override T arrayToObject(EzyArray array, EzyUnmarshaller unmarshaller) { T obj = (T)Activator.CreateInstance(objectType); PropertyInfo[] properties = objectType.GetProperties(); for (int i = 0; i < properties.Length; ++i) { PropertyInfo targetProperty = properties[i]; EzyValue anno = targetProperty.GetCustomAttribute <EzyValue>(); int index = anno != null ? anno.index : i; if (index >= array.size()) { continue; } Type outType = targetProperty.PropertyType; object rawValue = array.getByOutType(index, outType); if (rawValue == null) { continue; } object value = unmarshaller.unmarshallByOutType(rawValue, outType); if (targetProperty.PropertyType == value.GetType()) { targetProperty.SetValue(obj, value); } else { MethodInfo parseMethod = targetProperty.PropertyType.GetMethod( "TryParse", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string), targetProperty.PropertyType.MakeByRefType() }, null ); if (parseMethod != null) { object[] parameters = new[] { value, null }; bool success = (bool)parseMethod.Invoke(null, parameters); if (success) { targetProperty.SetValue(obj, parameters[1]); } } } } return(obj); }
public object unmarshallByOutType(object input, Type outType) { if (input == null) { return(null); } if (readerByOutType.ContainsKey(outType)) { IEzyReader reader = readerByOutType[outType]; return(reader.read(input, this)); } if (outType.IsGenericType) { if (typeof(IDictionary).IsAssignableFrom(outType) || typeof(IDictionary <,>) == outType.GetGenericTypeDefinition()) { Type dictType = typeof(Dictionary <,>); Type constructed = dictType.MakeGenericType(outType.GetGenericArguments()); IDictionary answer = (IDictionary)Activator.CreateInstance(constructed); EzyObject obj = (EzyObject)input; Type keyType = outType.GetGenericArguments()[0]; Type valueType = outType.GetGenericArguments()[1]; foreach (object key in obj.keys()) { answer[unmarshallByOutType(key, keyType)] = unmarshallByOutType(obj.getByOutType(key, valueType), valueType); } return(answer); } else if (typeof(IList).IsAssignableFrom(outType) || typeof(IList <>) == outType.GetGenericTypeDefinition()) { Type listType = typeof(List <>); Type constructed = listType.MakeGenericType(outType.GetGenericArguments()); IList answer = (IList)Activator.CreateInstance(constructed); EzyArray array = (EzyArray)input; Type valueType = outType.GetGenericArguments()[0]; for (int i = 0; i < array.size(); ++i) { Object rawValue = array.getByOutType(i, valueType); Object value = unmarshallByOutType(rawValue, valueType); answer.Add(value); } return(answer); } } return(input); }