コード例 #1
0
        /// <summary>
        /// Convert source type value to destination type value using <see cref="TypeConverter"/>
        /// applied to destination type.
        /// </summary>
        /// <param name="sourceType">A type of an source member.</param>
        /// <param name="destinationType">A type of an destination member.</param>
        /// <param name="source">A source instance.</param>
        /// <returns>A value converted with type converter or <c>null</c>.</returns>
        private static object FromConverter(Type sourceType, Type destinationType, object source)
        {
            TypeConverter converter = TypeConverterCache.GetConverter(destinationType);

            object destination = null;

            if (converter != null)
            {
                if (converter.CanConvertFrom(sourceType))
                {
                    destination = converter.ConvertFrom(source);
                }
                else if (converter.CanConvertFrom(typeof(string)))
                {
                    string str = source.ToString();

                    destination = converter.ConvertFromString(str);
                }
            }

            return(destination);
        }
コード例 #2
0
        /// <summary>
        /// Resolves type conversion between source and destination type.
        /// </summary>
        /// <returns>A possible conversion to try from source to destination type.</returns>
        public static TypeConversion Resolve(object sourceValue, Type sourceType, Type destinationType)
        {
            //// if types match or destination is assignable from source, direct assign is possible
            if (sourceType.Equals(destinationType) || destinationType.IsAssignableFrom(sourceType))
            {
                return(TypeConversion.Direct);
            }

            //// if destination type is enum and source type is enum underlying type or string,
            //// enum conversion is possible
            if (destinationType.IsEnum && (EnumUtility.IsEnumType(sourceType) || sourceType.Equals(typeof(string))))
            {
                return(TypeConversion.Enum);
            }

            //// if destination type has TypeConverter, then use that
            if (TypeConverterCache.HasConverter(destinationType))
            {
                return(TypeConversion.Converter);
            }

            //// if source is IConvertible, use System.Convert.ChangeType
            if (CanChangeType(sourceValue, destinationType))
            {
                return(TypeConversion.Convertable);
            }

            //// check if detination type has parsing methods
            if (ReflectionUtility.SupportsParsing(destinationType))
            {
                //// try string parsing conversion
                return(TypeConversion.String);
            }

            return(TypeConversion.None);
        }