示例#1
0
        private static ConvertResult TryConvertInternal(object initialValue, CultureInfo culture, Type targetType, out object value)
        {
            if (initialValue == null)
            {
                throw new ArgumentNullException("initialValue");
            }

            if (ReflectionUtils.IsNullableType(targetType))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
            }

            Type initialType = initialValue.GetType();

            if (targetType == initialType)
            {
                value = initialValue;
                return(ConvertResult.Success);
            }

            // use Convert.ChangeType if both types are IConvertible
            if (ConvertUtils.IsConvertible(initialValue.GetType()) && ConvertUtils.IsConvertible(targetType))
            {
                if (targetType.IsEnum())
                {
                    if (initialValue is string)
                    {
                        value = Enum.Parse(targetType, initialValue.ToString(), true);
                        return(ConvertResult.Success);
                    }
                    else if (IsInteger(initialValue))
                    {
                        value = Enum.ToObject(targetType, initialValue);
                        return(ConvertResult.Success);
                    }
                }

                value = System.Convert.ChangeType(initialValue, targetType, culture);
                return(ConvertResult.Success);
            }

#if !NET20
            if (initialValue is DateTime && targetType == typeof(DateTimeOffset))
            {
                value = new DateTimeOffset((DateTime)initialValue);
                return(ConvertResult.Success);
            }
#endif

            if (initialValue is byte[] && targetType == typeof(Guid))
            {
                value = new Guid((byte[])initialValue);
                return(ConvertResult.Success);
            }

            if (initialValue is Guid && targetType == typeof(byte[]))
            {
                value = ((Guid)initialValue).ToByteArray();
                return(ConvertResult.Success);
            }

            if (initialValue is string)
            {
                if (targetType == typeof(Guid))
                {
                    value = new Guid((string)initialValue);
                    return(ConvertResult.Success);
                }
                if (targetType == typeof(Uri))
                {
                    value = new Uri((string)initialValue, UriKind.RelativeOrAbsolute);
                    return(ConvertResult.Success);
                }
                if (targetType == typeof(TimeSpan))
                {
                    value = ParseTimeSpan((string)initialValue);
                    return(ConvertResult.Success);
                }
                if (targetType == typeof(byte[]))
                {
                    value = System.Convert.FromBase64String((string)initialValue);
                    return(ConvertResult.Success);
                }
                if (typeof(Type).IsAssignableFrom(targetType))
                {
                    value = Type.GetType((string)initialValue, true);
                    return(ConvertResult.Success);
                }
            }

#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
            if (targetType == typeof(BigInteger))
            {
                value = ToBigInteger(initialValue);
                return(ConvertResult.Success);
            }
            if (initialValue is BigInteger)
            {
                value = FromBigInteger((BigInteger)initialValue, targetType);
                return(ConvertResult.Success);
            }
#endif

#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
            // see if source or target types have a TypeConverter that converts between the two
            TypeConverter toConverter = GetConverter(initialType);

            if (toConverter != null && toConverter.CanConvertTo(targetType))
            {
                value = toConverter.ConvertTo(null, culture, initialValue, targetType);
                return(ConvertResult.Success);
            }

            TypeConverter fromConverter = GetConverter(targetType);

            if (fromConverter != null && fromConverter.CanConvertFrom(initialType))
            {
                value = fromConverter.ConvertFrom(null, culture, initialValue);
                return(ConvertResult.Success);
            }
#endif
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
            // handle DBNull and INullable
            if (initialValue == DBNull.Value)
            {
                if (ReflectionUtils.IsNullable(targetType))
                {
                    value = EnsureTypeAssignable(null, initialType, targetType);
                    return(ConvertResult.Success);
                }

                // cannot convert null to non-nullable
                value = null;
                return(ConvertResult.CannotConvertNull);
            }
#endif
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
            if (initialValue is INullable)
            {
                value = EnsureTypeAssignable(ToValue((INullable)initialValue), initialType, targetType);
                return(ConvertResult.Success);
            }
#endif

            if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract())
            {
                value = null;
                return(ConvertResult.NotInstantiableType);
            }

            value = null;
            return(ConvertResult.NoValidConversion);
        }
示例#2
0
        /// <summary>
        /// Converts the value to the specified type.
        /// </summary>
        /// <param name="initialValue">The value to convert.</param>
        /// <param name="culture">The culture to use when converting.</param>
        /// <param name="targetType">The type to convert the value to.</param>
        /// <returns>The converted type.</returns>
        public static object Convert(object initialValue, CultureInfo culture, Type targetType)
        {
            if (initialValue == null)
            {
                throw new ArgumentNullException("initialValue");
            }

            if (ReflectionUtils.IsNullableType(targetType))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
            }

            Type initialType = initialValue.GetType();

            if (targetType == initialType)
            {
                return(initialValue);
            }

            // use Convert.ChangeType if both types are IConvertible
            if (ConvertUtils.IsConvertible(initialValue.GetType()) && ConvertUtils.IsConvertible(targetType))
            {
                if (targetType.IsEnum())
                {
                    if (initialValue is string)
                    {
                        return(Enum.Parse(targetType, initialValue.ToString(), true));
                    }
                    else if (IsInteger(initialValue))
                    {
                        return(Enum.ToObject(targetType, initialValue));
                    }
                }

                return(System.Convert.ChangeType(initialValue, targetType, culture));
            }

            if (initialValue is DateTime && targetType == typeof(DateTimeOffset))
            {
                return(new DateTimeOffset((DateTime)initialValue));
            }

            if (initialValue is byte[] && targetType == typeof(Guid))
            {
                return(new Guid((byte[])initialValue));
            }

            if (initialValue is string)
            {
                if (targetType == typeof(Guid))
                {
                    return(new Guid((string)initialValue));
                }
                if (targetType == typeof(Uri))
                {
                    return(new Uri((string)initialValue, UriKind.RelativeOrAbsolute));
                }
                if (targetType == typeof(TimeSpan))
                {
                    return(ParseTimeSpan((string)initialValue));
                }
                if (typeof(Type).IsAssignableFrom(targetType))
                {
                    return(Type.GetType((string)initialValue, true));
                }
            }

            if (targetType == typeof(BigInteger))
            {
                return(ToBigInteger(initialValue));
            }
            if (initialValue is BigInteger)
            {
                return(FromBigInteger((BigInteger)initialValue, targetType));
            }

            if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract())
            {
                throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), "targetType");
            }

            throw new InvalidOperationException("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType));
        }
示例#3
0
        /// <summary>
        /// Converts the value to the specified type.
        /// </summary>
        /// <param name="initialValue">The value to convert.</param>
        /// <param name="culture">The culture to use when converting.</param>
        /// <param name="targetType">The type to convert the value to.</param>
        /// <returns>The converted type.</returns>
        public static object Convert(object initialValue, CultureInfo culture, Type targetType)
        {
            if (initialValue == null)
            {
                throw new ArgumentNullException("initialValue");
            }

            if (ReflectionUtils.IsNullableType(targetType))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
            }

            Type initialType = initialValue.GetType();

            if (targetType == initialType)
            {
                return(initialValue);
            }

            // use Convert.ChangeType if both types are IConvertible
            if (ConvertUtils.IsConvertible(initialValue.GetType()) && ConvertUtils.IsConvertible(targetType))
            {
                if (targetType.IsEnum())
                {
                    if (initialValue is string)
                    {
                        return(Enum.Parse(targetType, initialValue.ToString(), true));
                    }
                    else if (IsInteger(initialValue))
                    {
                        return(Enum.ToObject(targetType, initialValue));
                    }
                }

                return(System.Convert.ChangeType(initialValue, targetType, culture));
            }

#if !NET20
            if (initialValue is DateTime && targetType == typeof(DateTimeOffset))
            {
                return(new DateTimeOffset((DateTime)initialValue));
            }
#endif

            if (initialValue is byte[] && targetType == typeof(Guid))
            {
                return(new Guid((byte[])initialValue));
            }

            if (initialValue is string)
            {
                if (targetType == typeof(Guid))
                {
                    return(new Guid((string)initialValue));
                }
                if (targetType == typeof(Uri))
                {
                    return(new Uri((string)initialValue, UriKind.RelativeOrAbsolute));
                }
                if (targetType == typeof(TimeSpan))
                {
                    return(ParseTimeSpan((string)initialValue));
                }
                if (typeof(Type).IsAssignableFrom(targetType))
                {
                    return(Type.GetType((string)initialValue, true));
                }
            }

#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40 || PORTABLE)
            if (targetType == typeof(BigInteger))
            {
                return(ToBigInteger(initialValue));
            }
            if (initialValue is BigInteger)
            {
                return(FromBigInteger((BigInteger)initialValue, targetType));
            }
#endif

#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
            // see if source or target types have a TypeConverter that converts between the two
            TypeConverter toConverter = GetConverter(initialType);

            if (toConverter != null && toConverter.CanConvertTo(targetType))
            {
#if !SILVERLIGHT
                return(toConverter.ConvertTo(null, culture, initialValue, targetType));
#else
                return(toConverter.ConvertTo(initialValue, targetType));
#endif
            }

            TypeConverter fromConverter = GetConverter(targetType);

            if (fromConverter != null && fromConverter.CanConvertFrom(initialType))
            {
#if !SILVERLIGHT
                return(fromConverter.ConvertFrom(null, culture, initialValue));
#else
                return(fromConverter.ConvertFrom(initialValue));
#endif
            }
#endif
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
            // handle DBNull and INullable
            if (initialValue == DBNull.Value)
            {
                if (ReflectionUtils.IsNullable(targetType))
                {
                    return(EnsureTypeAssignable(null, initialType, targetType));
                }

                throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType));
            }
#endif
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE40 || PORTABLE || UNITY)
            if (initialValue is INullable)
            {
                return(EnsureTypeAssignable(ToValue((INullable)initialValue), initialType, targetType));
            }
#endif

            if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract())
            {
                throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), "targetType");
            }

            throw new InvalidOperationException("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType));
        }
        public static bool CanConvertType(Type initialType, Type targetType, bool allowTypeNameToString)
        {
            ValidationUtils.ArgumentNotNull(initialType, "initialType");
            ValidationUtils.ArgumentNotNull(targetType, "targetType");

            if (ReflectionUtils.IsNullableType(targetType))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
            }

            if (targetType == initialType)
            {
                return(true);
            }

            if (typeof(IConvertible).IsAssignableFrom(initialType) && typeof(IConvertible).IsAssignableFrom(targetType))
            {
                return(true);
            }

            if (initialType == typeof(DateTime) && targetType == typeof(DateTimeOffset))
            {
                return(true);
            }

            if (initialType == typeof(Guid) && (targetType == typeof(Guid) || targetType == typeof(string)))
            {
                return(true);
            }

            if (initialType == typeof(Type) && targetType == typeof(string))
            {
                return(true);
            }

#if !UNITY_WP8
            // see if source or target types have a TypeConverter that converts between the two
            TypeConverter toConverter = GetConverter(initialType);

            if (toConverter != null && !IsComponentConverter(toConverter) && toConverter.CanConvertTo(targetType))
            {
                if (allowTypeNameToString || toConverter.GetType() != typeof(TypeConverter))
                {
                    return(true);
                }
            }

            TypeConverter fromConverter = GetConverter(targetType);

            if (fromConverter != null && !IsComponentConverter(fromConverter) && fromConverter.CanConvertFrom(initialType))
            {
                return(true);
            }
#endif

            // handle DBNull and INullable
            if (initialType == typeof(DBNull))
            {
                if (ReflectionUtils.IsNullable(targetType))
                {
                    return(true);
                }
            }

            return(false);
        }
        /// <summary>
        /// Converts the value to the specified type.
        /// </summary>
        /// <param name="initialValue">The value to convert.</param>
        /// <param name="culture">The culture to use when converting.</param>
        /// <param name="targetType">The type to convert the value to.</param>
        /// <returns>The converted type.</returns>
        public static object Convert(object initialValue, CultureInfo culture, Type targetType)
        {
            if (initialValue == null)
            {
                throw new ArgumentNullException("initialValue");
            }

            if (ReflectionUtils.IsNullableType(targetType))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
            }

            Type initialType = initialValue.GetType();

            if (targetType == initialType)
            {
                return(initialValue);
            }

            if (initialValue is string && typeof(Type).IsAssignableFrom(targetType))
            {
                return(Type.GetType((string)initialValue, true));
            }

            if (targetType.IsInterface || targetType.IsGenericTypeDefinition || targetType.IsAbstract)
            {
                throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), "targetType");
            }

            // use Convert.ChangeType if both types are IConvertible
            if (initialValue is IConvertible && typeof(IConvertible).IsAssignableFrom(targetType))
            {
                if (targetType.IsEnum)
                {
                    if (initialValue is string)
                    {
                        return(Enum.Parse(targetType, initialValue.ToString(), true));
                    }
                    else if (IsInteger(initialValue))
                    {
                        return(Enum.ToObject(targetType, initialValue));
                    }
                }

                return(System.Convert.ChangeType(initialValue, targetType, culture));
            }

            if (initialValue is DateTime && targetType == typeof(DateTimeOffset))
            {
                return(new DateTimeOffset((DateTime)initialValue));
            }

            if (initialValue is string)
            {
                if (targetType == typeof(Guid))
                {
                    return(new Guid((string)initialValue));
                }
                if (targetType == typeof(Uri))
                {
                    return(new Uri((string)initialValue));
                }
                if (targetType == typeof(TimeSpan))
                {
                    return(TimeSpan.Parse((string)initialValue));
                }
            }

#if !UNITY_WP8
            // see if source or target types have a TypeConverter that converts between the two
            TypeConverter toConverter = GetConverter(initialType);

            if (toConverter != null && toConverter.CanConvertTo(targetType))
            {
#if !UNITY_WP8
                return(toConverter.ConvertTo(null, culture, initialValue, targetType));
#else
                return(toConverter.ConvertTo(initialValue, targetType));
#endif
            }

            TypeConverter fromConverter = GetConverter(targetType);

            if (fromConverter != null && fromConverter.CanConvertFrom(initialType))
            {
#if !UNITY_WP8
                return(fromConverter.ConvertFrom(null, culture, initialValue));
#else
                return(fromConverter.ConvertFrom(initialValue));
#endif
            }
#endif

            // handle DBNull and INullable
            if (initialValue == DBNull.Value)
            {
                if (ReflectionUtils.IsNullable(targetType))
                {
                    return(EnsureTypeAssignable(null, initialType, targetType));
                }

                throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType));
            }

            throw new Exception("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType));
        }
示例#6
0
        public static object Convert(object initialValue, CultureInfo culture, Type targetType)
        {
            if (initialValue == null)
            {
                throw new ArgumentNullException("initialValue");
            }
            if (ReflectionUtils.IsNullableType(targetType))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
            }
            Type type = initialValue.GetType();

            if (targetType == type)
            {
                return(initialValue);
            }
            if (initialValue is string && typeof(Type).IsAssignableFrom(targetType))
            {
                return(Type.GetType((string)initialValue, throwOnError: true));
            }
            if (targetType.IsInterface || targetType.IsGenericTypeDefinition || targetType.IsAbstract)
            {
                throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), "targetType");
            }
            if (initialValue is IConvertible && typeof(IConvertible).IsAssignableFrom(targetType))
            {
                if (targetType.IsEnum)
                {
                    if (initialValue is string)
                    {
                        return(Enum.Parse(targetType, initialValue.ToString(), ignoreCase: true));
                    }
                    if (IsInteger(initialValue))
                    {
                        return(Enum.ToObject(targetType, initialValue));
                    }
                }
                return(System.Convert.ChangeType(initialValue, targetType, culture));
            }
            if (initialValue is DateTime && targetType == typeof(DateTimeOffset))
            {
                return(new DateTimeOffset((DateTime)initialValue));
            }
            if (initialValue is string)
            {
                if (targetType == typeof(Guid))
                {
                    return(new Guid((string)initialValue));
                }
                if (targetType == typeof(Uri))
                {
                    return(new Uri((string)initialValue));
                }
                if (targetType == typeof(TimeSpan))
                {
                    return(TimeSpan.Parse((string)initialValue));
                }
            }
            TypeConverter converter = GetConverter(type);

            if (converter != null && converter.CanConvertTo(targetType))
            {
                return(converter.ConvertTo(null, culture, initialValue, targetType));
            }
            TypeConverter converter2 = GetConverter(targetType);

            if (converter2 != null && converter2.CanConvertFrom(type))
            {
                return(converter2.ConvertFrom(null, culture, initialValue));
            }
            if (initialValue == DBNull.Value)
            {
                if (ReflectionUtils.IsNullable(targetType))
                {
                    return(EnsureTypeAssignable(null, type, targetType));
                }
                throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, type, targetType));
            }
            throw new Exception("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, type, targetType));
        }
 public static Type EnsureNotNullableType(Type t)
 {
     return((!ReflectionUtils.IsNullableType(t)) ? t : Nullable.GetUnderlyingType(t));
 }
 public static bool IsNullable(Type t)
 {
     ValidationUtils.ArgumentNotNull(t, "t");
     return(!t.IsValueType || ReflectionUtils.IsNullableType(t));
 }
示例#9
0
 private static bool IsCompatibleObject(object value) =>
 ((value is T) || ((value == null) && (!typeof(T).IsValueType() || ReflectionUtils.IsNullableType(typeof(T)))));
示例#10
0
 public static bool IsNullable(Type t)
 {
     ValidationUtils.ArgumentNotNull((object)t, nameof(t));
     return(!t.IsValueType() || ReflectionUtils.IsNullableType(t));
 }