Ejemplo n.º 1
0
        public static GetMemberDelegate CreateTypeConverter(Type fromType, Type toType)
        {
            if (fromType == toType)
            {
                return(null);
            }

            var converter = AutoMappingUtils.GetConverter(fromType, toType);

            if (converter != null)
            {
                return(converter);
            }

            if (fromType == typeof(string))
            {
                return(fromValue => TypeSerializer.DeserializeFromString((string)fromValue, toType));
            }

            if (toType == typeof(string))
            {
                return(o => TypeSerializer.SerializeToString(o).StripQuotes());
            }

            var underlyingToType   = Nullable.GetUnderlyingType(toType) ?? toType;
            var underlyingFromType = Nullable.GetUnderlyingType(fromType) ?? fromType;

            if (underlyingToType.IsEnum)
            {
                if (underlyingFromType.IsEnum || fromType == typeof(string))
                {
                    return(fromValue => Enum.Parse(underlyingToType, fromValue.ToString(), ignoreCase: true));
                }

                if (underlyingFromType.IsIntegerType())
                {
                    return(fromValue => Enum.ToObject(underlyingToType, fromValue));
                }
            }
            else if (underlyingFromType.IsEnum)
            {
                if (underlyingToType.IsIntegerType())
                {
                    return(fromValue => Convert.ChangeType(fromValue, underlyingToType, null));
                }
            }
            else if (typeof(IEnumerable).IsAssignableFrom(fromType) && underlyingToType != typeof(string))
            {
                return(fromValue => AutoMappingUtils.TryConvertCollections(fromType, underlyingToType, fromValue));
            }
            else if (underlyingToType.IsValueType)
            {
                return(fromValue => AutoMappingUtils.ChangeValueType(fromValue, underlyingToType));
            }
            else
            {
                return(fromValue =>
                {
                    if (fromValue == null)
                    {
                        return fromValue;
                    }
                    if (toType == typeof(string))
                    {
                        return fromValue.ToJsv();
                    }

                    var toValue = toType.CreateInstance();
                    toValue.PopulateWith(fromValue);
                    return toValue;
                });
            }

            return(null);
        }