Exemplo n.º 1
0
        /// <summary>
        /// Converts an object to the target type.
        /// </summary>
        /// <param name="sourceInstance">The object to convert to the target type.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <returns>The converted object.</returns>
        /// <remarks>
        /// <para>
        /// Converts an object to the target type.
        /// </para>
        /// </remarks>
        public static object ConvertTypeTo(object sourceInstance, Type targetType)
        {
            Type sourceType = sourceInstance.GetType();

            // Check if we can assign directly from the source type to the target type
            if (targetType.IsAssignableFrom(sourceType))
            {
                return(sourceInstance);
            }

            // Look for a TO converter
            IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType);

            if (tcSource != null)
            {
                if (tcSource.CanConvertTo(targetType))
                {
                    return(tcSource.ConvertTo(sourceInstance, targetType));
                }
            }

            // Look for a FROM converter
            IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType);

            if (tcTarget != null)
            {
                if (tcTarget.CanConvertFrom(sourceType))
                {
                    return(tcTarget.ConvertFrom(sourceInstance));
                }
            }

            throw new ArgumentException("Cannot convert source object [" + sourceInstance.ToString() + "] to target type [" + targetType.Name + "]", "sourceInstance");
        }
        /// <summary>
        /// Gets the type converter to use to convert values to the destination type.
        /// </summary>
        /// <param name="destinationType">The type being converted to.</param>
        /// <returns>
        /// The type converter instance to use for type conversions or <c>null</c>
        /// if no type converter is found.
        /// </returns>
        /// <remarks>
        /// <para>
        /// Gets the type converter to use to convert values to the destination type.
        /// </para>
        /// </remarks>
        public static IConvertFrom GetConvertFrom(Type destinationType)
        {
            // TODO: Support inheriting type converters.
            // i.e. getting a type converter for a base of destinationType

            lock (s_type2converter)
            {
                // Lookup in the static registry
                IConvertFrom converter = s_type2converter[destinationType] as IConvertFrom;

                if (converter == null)
                {
                    // Lookup using attributes
                    converter = GetConverterFromAttribute(destinationType) as IConvertFrom;

                    if (converter != null)
                    {
                        // Store in registry
                        s_type2converter[destinationType] = converter;
                    }
                }

                return(converter);
            }
        }
		/// <summary>
		/// Adds a converter for a specific type.
		/// </summary>
		/// <param name="destinationType">The type being converted to.</param>
		/// <param name="converter">The type converter to use to convert to the destination type.</param>
		public static void AddConverter(Type destinationType, IConvertFrom converter)
		{
			if (destinationType != null && converter != null)
			{
				s_registry[destinationType] = converter;
			}
		}
Exemplo n.º 4
0
        public static object ConvertStringTo(Type target, string txt)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }
            if (ReferenceEquals(typeof(string), target) || ReferenceEquals(typeof(object), target))
            {
                return(txt);
            }
            IConvertFrom convertFrom = ConverterRegistry.GetConvertFrom(target);

            if ((convertFrom != null) && convertFrom.CanConvertFrom(typeof(string)))
            {
                return(convertFrom.ConvertFrom(txt));
            }
            if (target.IsEnum)
            {
                return(ParseEnum(target, txt, true));
            }
            Type[]     types  = new Type[] { typeof(string) };
            MethodInfo method = target.GetMethod("Parse", types);

            if (method == null)
            {
                return(null);
            }
            object[] parameters = new object[] { txt };
            return(method.Invoke(null, BindingFlags.InvokeMethod, null, parameters, CultureInfo.InvariantCulture));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Converts a string to an object.
        /// </summary>
        /// <param name="target">The target type to convert to.</param>
        /// <param name="txt">The string to convert to an object.</param>
        /// <returns>
        /// The object converted from a string or <c>null</c> when the
        /// conversion failed.
        /// </returns>
        /// <remarks>
        /// <para>
        /// Converts a string to an object. Uses the converter registry to try
        /// to convert the string value into the specified target type.
        /// </para>
        /// </remarks>
        public static object ConvertStringTo(Type target, string txt)
        {
            if ((object)target == null)
            {
                throw new ArgumentNullException("target");
            }
            if ((object)typeof(string) == target || (object)typeof(object) == target)
            {
                return(txt);
            }
            IConvertFrom convertFrom = ConverterRegistry.GetConvertFrom(target);

            if (convertFrom != null && convertFrom.CanConvertFrom(typeof(string)))
            {
                return(convertFrom.ConvertFrom(txt));
            }
            if (target.GetTypeInfo().IsEnum)
            {
                return(ParseEnum(target, txt, ignoreCase: true));
            }
            return(target.GetMethod("Parse", new Type[1]
            {
                typeof(string)
            })?.Invoke(target, new string[1]
            {
                txt
            }));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Checks if there is an apropriate type conversion from the source type to the target type.
        /// </summary>
        /// <param name="sourceType">The type to convert from.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <returns><c>true</c> if there is a conversion from the source type to the target type.</returns>
        public static bool CanConvertTypeTo(Type sourceType, Type targetType)
        {
            if (sourceType == null || targetType == null)
            {
                return(false);
            }

            // Check if we can assign directly from the source type to the target type
            if (targetType.IsAssignableFrom(sourceType))
            {
                return(true);
            }

            IConvertFrom tcTarget = GetTypeConverter(targetType);

            if (tcTarget != null)
            {
                if (tcTarget.CanConvertFrom(sourceType))
                {
                    return(true);
                }
            }

            return(false);
        }
 /// <summary>
 /// Adds a converter for a specific type.
 /// </summary>
 /// <param name="destinationType">The type being converted to.</param>
 /// <param name="converter">The type converter to use to convert to the destination type.</param>
 public static void AddConverter(Type destinationType, IConvertFrom converter)
 {
     if (destinationType != null && converter != null)
     {
         s_registry[destinationType] = converter;
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// Converts a string to an object.
        /// </summary>
        /// <param name="target">The target type to convert to.</param>
        /// <param name="txt">The string to convert to an object.</param>
        /// <returns>
        /// The object converted from a string or <c>null</c> when the
        /// conversion failed.
        /// </returns>
        /// <remarks>
        /// <para>
        /// Converts a string to an object. Uses the converter registry to try
        /// to convert the string value into the specified target type.
        /// </para>
        /// </remarks>
        public static object ConvertStringTo(Type target, string txt)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            // If we want a string we already have the correct type
            if (typeof(string) == target || typeof(object) == target)
            {
                return(txt);
            }

            // First lets try to find a type converter
            IConvertFrom typeConverter = ConverterRegistry.GetConvertFrom(target);

            if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string)))
            {
                // Found appropriate converter
                return(typeConverter.ConvertFrom(txt));
            }
            else
            {
#if NETSTANDARD1_3
                if (target.GetTypeInfo().IsEnum)
#else
                if (target.IsEnum)
#endif
                {
                    // Target type is an enum.

                    // Use the Enum.Parse(EnumType, string) method to get the enum value
                    return(ParseEnum(target, txt, true));
                }
                else
                {
                    // We essentially make a guess that to convert from a string
                    // to an arbitrary type T there will be a static method defined on type T called Parse
                    // that will take an argument of type string. i.e. T.Parse(string)->T we call this
                    // method to convert the string to the type required by the property.
                    System.Reflection.MethodInfo meth = target.GetMethod("Parse", new Type[] { typeof(string) });
                    if (meth != null)
                    {
                        // Call the Parse method
#if NETSTANDARD1_3
                        return(meth.Invoke(target, new[] { txt }));
#else
                        return(meth.Invoke(null, BindingFlags.InvokeMethod, null, new object[] { txt }, CultureInfo.InvariantCulture));
#endif
                    }
                    else
                    {
                        // No Parse() method found.
                    }
                }
            }

            return(null);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Looks up the <see cref="IConvertFrom"/> for the target type.
        /// </summary>
        /// <param name="target">The type to lookup the converter for.</param>
        /// <returns>The converter for the specified type.</returns>
        public static IConvertFrom GetTypeConverter(Type target)
        {
            IConvertFrom converter = ConverterRegistry.GetConverter(target);

            if (converter == null)
            {
                throw new InvalidOperationException("No type converter defined for [" + target + "]");
            }
            return(converter);
        }
Exemplo n.º 10
0
 public static IConvertFrom GetConvertFrom(Type destinationType)
 {
     lock (s_type2converter)
     {
         IConvertFrom converterFromAttribute = s_type2converter[destinationType] as IConvertFrom;
         if (converterFromAttribute == null)
         {
             converterFromAttribute = GetConverterFromAttribute(destinationType) as IConvertFrom;
             if (converterFromAttribute != null)
             {
                 s_type2converter[destinationType] = converterFromAttribute;
             }
         }
         return(converterFromAttribute);
     }
 }
Exemplo n.º 11
0
        public static bool CanConvertTypeTo(Type sourceType, Type targetType)
        {
            if ((sourceType == null) || (targetType == null))
            {
                return(false);
            }
            if (targetType.IsAssignableFrom(sourceType))
            {
                return(true);
            }
            IConvertTo convertTo = ConverterRegistry.GetConvertTo(sourceType, targetType);

            if ((convertTo != null) && convertTo.CanConvertTo(targetType))
            {
                return(true);
            }
            IConvertFrom convertFrom = ConverterRegistry.GetConvertFrom(targetType);

            return((convertFrom != null) && convertFrom.CanConvertFrom(sourceType));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Converts an object to the target type.
        /// </summary>
        /// <param name="sourceObject">The object to convert to the target type.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <returns>The converted object.</returns>
        public static object ConvertTypeTo(object sourceObject, Type targetType)
        {
            Type sourceType = sourceObject.GetType();

            // Check if we can assign directly from the source type to the target type
            if (targetType.IsAssignableFrom(sourceType))
            {
                return(sourceObject);
            }

            IConvertFrom tcTarget = GetTypeConverter(targetType);

            if (tcTarget != null)
            {
                if (tcTarget.CanConvertFrom(sourceType))
                {
                    return(tcTarget.ConvertFrom(sourceObject));
                }
            }

            throw new ArgumentException("Cannot convert source object [" + sourceObject.ToString() + "] to target type [" + targetType.Name + "]", "sourceObject");
        }
Exemplo n.º 13
0
        /// <summary>
        /// Converts an object to the target type.
        /// </summary>
        /// <param name="sourceInstance">The object to convert to the target type.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <returns>The converted object.</returns>
        /// <remarks>
        /// <para>
        /// Converts an object to the target type.
        /// </para>
        /// </remarks>
        public static object ConvertTypeTo(object sourceInstance, Type targetType)
        {
            Type type = sourceInstance.GetType();

            if (CompatibilityExtensions.IsAssignableFrom(targetType, type))
            {
                return(sourceInstance);
            }
            IConvertTo convertTo = ConverterRegistry.GetConvertTo(type, targetType);

            if (convertTo != null && convertTo.CanConvertTo(targetType))
            {
                return(convertTo.ConvertTo(sourceInstance, targetType));
            }
            IConvertFrom convertFrom = ConverterRegistry.GetConvertFrom(targetType);

            if (convertFrom != null && convertFrom.CanConvertFrom(type))
            {
                return(convertFrom.ConvertFrom(sourceInstance));
            }
            throw new ArgumentException("Cannot convert source object [" + sourceInstance.ToString() + "] to target type [" + targetType.Name + "]", "sourceInstance");
        }
Exemplo n.º 14
0
        public static object ConvertTypeTo(object sourceInstance, Type targetType)
        {
            Type c = sourceInstance.GetType();

            if (targetType.IsAssignableFrom(c))
            {
                return(sourceInstance);
            }
            IConvertTo convertTo = ConverterRegistry.GetConvertTo(c, targetType);

            if ((convertTo != null) && convertTo.CanConvertTo(targetType))
            {
                return(convertTo.ConvertTo(sourceInstance, targetType));
            }
            IConvertFrom convertFrom = ConverterRegistry.GetConvertFrom(targetType);

            if ((convertFrom != null) && convertFrom.CanConvertFrom(c))
            {
                return(convertFrom.ConvertFrom(sourceInstance));
            }
            string[] textArray1 = new string[] { "Cannot convert source object [", sourceInstance.ToString(), "] to target type [", targetType.Name, "]" };
            throw new ArgumentException(string.Concat(textArray1), "sourceInstance");
        }
Exemplo n.º 15
0
        // /// <summary>
        // /// Looks up the <see cref="IConvertFrom"/> for the target type.
        // /// </summary>
        // /// <param name="target">The type to lookup the converter for.</param>
        // /// <returns>The converter for the specified type.</returns>
        // public static IConvertFrom GetTypeConverter(Type target)
        // {
        // IConvertFrom converter = ConverterRegistry.GetConverter(target);
        // if (converter == null)
        // {
        // throw new InvalidOperationException("No type converter defined for [" + target + "]");
        // }
        // return converter;
        // }

        /// <summary>
        /// Checks if there is an appropriate type conversion from the source type to the target type.
        /// </summary>
        /// <param name="sourceType">The type to convert from.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <returns><c>true</c> if there is a conversion from the source type to the target type.</returns>
        /// <remarks>
        /// Checks if there is an appropriate type conversion from the source type to the target type.
        /// <para>
        /// </para>
        /// </remarks>
        public static bool CanConvertTypeTo(Type sourceType, Type targetType)
        {
            if (sourceType == null || targetType == null)
            {
                return(false);
            }

            // Check if we can assign directly from the source type to the target type
            if (targetType.IsAssignableFrom(sourceType))
            {
                return(true);
            }

            // Look for a To converter
            IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType);

            if (tcSource != null)
            {
                if (tcSource.CanConvertTo(targetType))
                {
                    return(true);
                }
            }

            // Look for a From converter
            IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType);

            if (tcTarget != null)
            {
                if (tcTarget.CanConvertFrom(sourceType))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Checks if there is an appropriate type conversion from the source type to the target type.
        /// </summary>
        /// <param name="sourceType">The type to convert from.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <returns><c>true</c> if there is a conversion from the source type to the target type.</returns>
        /// <remarks>
        /// Checks if there is an appropriate type conversion from the source type to the target type.
        /// <para>
        /// </para>
        /// </remarks>
        public static bool CanConvertTypeTo(Type sourceType, Type targetType)
        {
            if ((object)sourceType == null || (object)targetType == null)
            {
                return(false);
            }
            if (CompatibilityExtensions.IsAssignableFrom(targetType, sourceType))
            {
                return(true);
            }
            IConvertTo convertTo = ConverterRegistry.GetConvertTo(sourceType, targetType);

            if (convertTo != null && convertTo.CanConvertTo(targetType))
            {
                return(true);
            }
            IConvertFrom convertFrom = ConverterRegistry.GetConvertFrom(targetType);

            if (convertFrom != null && convertFrom.CanConvertFrom(sourceType))
            {
                return(true);
            }
            return(false);
        }