CanConvertTo() 공개 메소드

public CanConvertTo ( ITypeDescriptorContext context, Type destinationType ) : bool
context ITypeDescriptorContext
destinationType Type
리턴 bool
예제 #1
0
		public void CheckConvert(int expect_from, int expect_to, TypeConverter conv, Type type) {
			int from_count	 = 0;
			int to_count	 = 0;

			foreach (Type t in typeof(int).Assembly.GetTypes ()) {
				if (conv.CanConvertFrom(null, t)) {
					from_count++;
					if (debug > 0) {
						Console.WriteLine("{0}: Conversion from {1} supported", conv.ToString(), t.ToString());
					}
				}

				if (conv.CanConvertTo(null, t)) {
					to_count++;
					if (debug > 0) {
						Console.WriteLine("{0}: Conversion to {1} supported", conv.ToString(), t.ToString());
					}
				}
			}

#if not
			foreach (Type t in type.Assembly.GetTypes ()) {
				if (conv.CanConvertFrom(null, t)) {
					from_count++;
					if (debug > 0) {
						Console.WriteLine("{0}: Conversion from {1} supported", conv.ToString(), t.ToString());
					}
				}

				if (conv.CanConvertTo(null, t)) {
					to_count++;
					if (debug > 0) {
						Console.WriteLine("{0}: Conversion to {1} supported", conv.ToString(), t.ToString());
					}
				}
			}
#endif

			if (from_count != expect_from) {
				if (verbose > 0) {
					Console.WriteLine("{0}: ConvertFrom expected {1}, returned {2}", conv.ToString(), expect_from, from_count);
				}
				failed++;
			}

			if (to_count != expect_to) {
				if (verbose > 0) {
					Console.WriteLine("{0}: ConvertTo expected {1}, returned {2}", conv.ToString(), expect_to, to_count);
				}
				failed++;
			}

		}
예제 #2
0
        private static object DoConversion(object value, Type toType, CultureInfo culture)
        {
            if ((value is IConvertible) || (value == null))
            {
                try
                {
                    return(System.Convert.ChangeType(value, toType, culture));
                }
                catch (Exception)
                {
                    return(DependencyProperty.UnsetValue);
                }
            }
            else
            {
                System.ComponentModel.TypeConverter typeConverter = TypeDescriptor.GetConverter(value);

                if (typeConverter.CanConvertTo(toType))
                {
                    return(typeConverter.ConvertTo(null, culture, value, toType));
                }
            }

            return(DependencyProperty.UnsetValue);
        }
예제 #3
0
        /// <summary>
        /// 转换简单类型
        /// </summary>
        /// <param name="value"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static object ConvertObj(object value, Type type)
        {
            object returnValue;

            if ((value == null) || type.IsInstanceOfType(value))
            {
                return(value);
            }
            string str = value as string;

            if ((str != null) && (str.Length == 0))
            {
                return(null);
            }
            System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type);
            bool flag = converter.CanConvertFrom(value.GetType());

            if (!flag)
            {
                converter = TypeDescriptor.GetConverter(value.GetType());
            }
            if (!flag && !converter.CanConvertTo(type))
            {
                throw new InvalidOperationException("无法转换成类型:" + value.ToString() + "==>" + type);
            }
            try
            {
                returnValue = flag ? converter.ConvertFrom(null, null, value) : converter.ConvertTo(null, null, value, type);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("类型转换出错:" + value.ToString() + "==>" + type, e);
            }
            return(returnValue);
        }
예제 #4
0
 protected internal ModelValueProperty(ModelType declaringType, string name, string label, string helptext, string format, bool isStatic, Type propertyType, TypeConverter converter, bool isList = false, bool isReadOnly = false, bool isPersisted = true, Attribute[] attributes = null, LambdaExpression defaultValue = null)
     : base(declaringType, name, label, helptext, format, isStatic, isList, isReadOnly, isPersisted, attributes)
 {
     this.PropertyType = propertyType;
     this.Converter = converter;
     this.AutoConvert = converter != null && converter.CanConvertTo(typeof(object));
     this.FormatProvider = declaringType.GetFormatProvider(propertyType);
     if (defaultValue != null)
     {
         if (defaultValue.Parameters.Count > 0)
             throw new ArgumentException("Default value expressions cannot have parameters.");
         if (propertyType.IsAssignableFrom(defaultValue.Type))
             throw new ArgumentException("Default value expressions must match the type of the property they are for.");
         this.DefaultValue = defaultValue;
     }
 }
예제 #5
0
        private static object ConvertSimpleType(CultureInfo culture, object value, Type destinationType)
        {
            if (value == null || destinationType.IsInstanceOfType(value))
            {
                return(value);
            }

            // if this is a user-input value but the user didn't type anything, return no value
            string valueAsString = value as string;

            if (valueAsString != null && valueAsString.Trim().Length == 0)
            {
                return(null);
            }

            //modified by Yang Li
            //TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
            System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
            bool canConvertFrom = converter.CanConvertFrom(value.GetType());

            if (!canConvertFrom)
            {
                converter = TypeDescriptor.GetConverter(value.GetType());
            }
            if (!(canConvertFrom || converter.CanConvertTo(destinationType)))
            {
                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_NoConverterExists,
                                               value.GetType().FullName, destinationType.FullName);
                throw new InvalidOperationException(message);
            }

            try
            {
                object convertedValue = (canConvertFrom) ?
                                        converter.ConvertFrom(null /* context */, culture, value) :
                                        converter.ConvertTo(null /* context */, culture, value, destinationType);
                return(convertedValue);
            }
            catch (Exception ex)
            {
                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_ConversionThrew,
                                               value.GetType().FullName, destinationType.FullName);
                throw new InvalidOperationException(message, ex);
            }
        }
예제 #6
0
		public virtual object ParseFormattedValue (object formattedValue, DataGridViewCellStyle cellStyle, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter)
		{
			if (cellStyle == null)
				throw new ArgumentNullException ("cellStyle is null.");
			if (FormattedValueType == null)
				throw new FormatException ("The System.Windows.Forms.DataGridViewCell.FormattedValueType property value is null.");
			if (formattedValue == null)
				throw new ArgumentException ("formattedValue is null.");
			if (ValueType == null)
				throw new FormatException ("valuetype is null");
			if (!FormattedValueType.IsAssignableFrom (formattedValue.GetType ()))
				throw new ArgumentException ("formattedValue is not of formattedValueType.");
			
			if (formattedValueTypeConverter == null)
				formattedValueTypeConverter = FormattedValueTypeConverter;
			if (valueTypeConverter == null)
				valueTypeConverter = ValueTypeConverter;

			if (valueTypeConverter != null && valueTypeConverter.CanConvertFrom (FormattedValueType))
				return valueTypeConverter.ConvertFrom (formattedValue);
			if (formattedValueTypeConverter != null && formattedValueTypeConverter.CanConvertTo (ValueType))
				return formattedValueTypeConverter.ConvertTo (formattedValue, ValueType);
			return Convert.ChangeType (formattedValue, ValueType);
		}
예제 #7
0
        public static bool Convert(object val, Type targetType, out object result)
        {
            result = val;
            // Trivial cases
            if (val == null)
            {
                // Cannot convert null to value type
                return(!targetType.IsValueType);
            }
            if (targetType.IsAssignableFrom(val.GetType()))
            {
                return(true);
            }

            // Custom type conversions

            if (_customTypeConverter != null)
            {
                if (_customTypeConverter(val, targetType, out result))
                {
                    return(true);
                }
            }

            // TODO: typeof(Nullable<T>)

            // Built-in type conversions

            if (val.GetType() == typeof(string) && targetType == typeof(Type))
            { // string -> Type
                result = Type.GetType(val.ToString());
                return(result != null);
            }

            // Enumerations
            if (val.GetType() == typeof(string) && targetType.IsEnum)
            { // string -> Enum
                result = Enum.Parse(targetType, (string)val);
                return(true);
            }

            // String target type must be done before enumerations are tried - else, the string will be treated as enumeration
            if (targetType.IsAssignableFrom(typeof(string)))
            { // * -> string
                result = val.ToString();
                return(true);
            }

            // Collection types

            Type enumerableType;
            Type entryType;

            ReflectionHelper.FindImplementedEnumerableType(targetType, out enumerableType, out entryType);

            if (enumerableType != null) // Targets IList, ICollection, IList<>, ICollection<>
            {
                ICollection col;
                if (!ToCollection(val, entryType, out col))
                {
                    return(false);
                }
                List <object> resultList = col.Cast <object>().ToList();
                result = resultList;
                return(true);
            }
            ICollection sourceCol = val as ICollection;

            if (sourceCol != null && sourceCol.Count == 1) // From collection to non-collection target
            {
                // Use the first (single) item of a collection or dictionary
                IEnumerator enumerator = sourceCol.GetEnumerator();
                enumerator.MoveNext();
                object item = enumerator.Current;
                if (Convert(item, targetType, out result)) // Single collection item
                {
                    return(true);
                }
                KeyValuePair <object, object>?kvp = item as KeyValuePair <object, object>?;
                if (kvp.HasValue && Convert(kvp.Value.Value, targetType, out result)) // Value of single dictionary entry - generic dictionary
                {
                    IDisposable d = kvp.Value.Key as IDisposable;
                    if (d != null)
                    {
                        d.Dispose();
                    }
                    return(true);
                }
                DictionaryEntry?entry = item as DictionaryEntry?;
                if (entry.HasValue && Convert(entry.Value.Value, targetType, out result)) // Value of single dictionary entry - legacy dictionary
                {
                    IDisposable d = entry.Value.Key as IDisposable;
                    if (d != null)
                    {
                        d.Dispose();
                    }
                    return(true);
                }
            }

            // Simple type conversions

            System.ComponentModel.TypeConverter tc = TypeDescriptor.GetConverter(targetType);
            if (tc != null && tc.CanConvertFrom(val.GetType()))
            {
                try
                {
                    result = tc.ConvertFrom(null, CultureInfo.InvariantCulture, val);
                    return(true);
                }
                catch { }
            }

            tc = TypeDescriptor.GetConverter(val);
            if (tc != null && tc.CanConvertTo(targetType))
            {
                result = tc.ConvertTo(val, targetType);
                return(true);
            }

            return(false);
        }
예제 #8
0
 /// <summary>
 /// This method checks whether the specified object can be converted to string.
 /// </summary>
 /// <param name="rawValue">Value to check</param>
 /// <param name="converter">Type converter object</param>
 /// <returns>
 /// True, if the type can be converted to string; otherwise, false;
 /// </returns>
 public static bool CanConvertToString(object rawValue, out TypeConverter converter)
 {
     var valueType = rawValue.GetType();
     converter = TypeDescriptor.GetConverter(valueType);
     return converter != null && converter.CanConvertTo(typeof(String));
 }
예제 #9
0
파일: formatter.cs 프로젝트: JianwenSun/cc
        /// <devdoc>
        ///
        /// Converts a value into a format suitable for display to the end user.
        ///
        /// - Converts DBNull or null into a suitable formatted representation of 'null'
        /// - Performs some special-case conversions (eg. Boolean to CheckState)
        /// - Uses TypeConverters or IConvertible where appropriate
        /// - Throws a FormatException is no suitable conversion can be found
        ///
        /// </devdoc>
        private static object FormatObjectInternal(object value,
                                                   Type targetType, 
                                                   TypeConverter sourceConverter, 
                                                   TypeConverter targetConverter, 
                                                   string formatString, 
                                                   IFormatProvider formatInfo, 
                                                   object formattedNullValue) {
            if (value == System.DBNull.Value || value == null) {
                //
                // Convert DBNull to the formatted representation of 'null' (if possible)
                //
                if (formattedNullValue != null)
                {
                    return formattedNullValue;
                }

                //
                // Convert DBNull or null to a specific 'known' representation of null (otherwise fail)
                //
                if (targetType == stringType)
                {
                    return String.Empty;
                }
                
                if (targetType == checkStateType) {
                    return CheckState.Indeterminate;
                }
                
                // Just pass null through: if this is a value type, it's been unwrapped here, so we return null 
                // and the caller has to wrap if appropriate.
                return null; 
            }

            //
            // Special case conversions
            //

            if (targetType == stringType) {
                if (value is IFormattable && !String.IsNullOrEmpty(formatString)) {
                    return (value as IFormattable).ToString(formatString, formatInfo);
                }
            }

            //The converters for properties should take precedence.  Unfortunately, we don't know whether we have one.  Check vs. the 
            //type's TypeConverter.  We're punting the case where the property-provided converter is the same as the type's converter.
            Type sourceType = value.GetType();
            TypeConverter sourceTypeTypeConverter = TypeDescriptor.GetConverter(sourceType);
            if (sourceConverter != null && sourceConverter != sourceTypeTypeConverter && sourceConverter.CanConvertTo(targetType)) {
                return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
            }

            TypeConverter targetTypeTypeConverter = TypeDescriptor.GetConverter(targetType);
            if (targetConverter != null && targetConverter != targetTypeTypeConverter && targetConverter.CanConvertFrom(sourceType)) {
                return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
            }

            if (targetType == checkStateType) {
                if (sourceType == booleanType) {
                    return ((bool)value) ? CheckState.Checked : CheckState.Unchecked;
                } 
                else {
                    if (sourceConverter == null) {
                        sourceConverter = sourceTypeTypeConverter;
                    }
                    if (sourceConverter != null && sourceConverter.CanConvertTo(booleanType)) {
                        return (bool)sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, booleanType)
                            ? CheckState.Checked : CheckState.Unchecked;
                    }
                }
            }

            if (targetType.IsAssignableFrom(sourceType)) {
                return value;
            }

            //
            // If explicit type converters not provided, supply default ones instead
            //

            if (sourceConverter == null) {
                sourceConverter = sourceTypeTypeConverter;
            }

            if (targetConverter == null) {
                targetConverter = targetTypeTypeConverter;
            }

            //
            // Standardized conversions
            //

            if (sourceConverter != null && sourceConverter.CanConvertTo(targetType)) {
                return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
            }
            else if (targetConverter != null && targetConverter.CanConvertFrom(sourceType)) {
                return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
            }
            else if (value is IConvertible) {
                return ChangeType(value, targetType, formatInfo);
            }

            //
            // Fail if no suitable conversion found
            //

            throw new FormatException(GetCantConvertMessage(value, targetType));
        }
예제 #10
0
파일: formatter.cs 프로젝트: JianwenSun/cc
        /// <devdoc>
        ///
        /// Converts a value entered by the end user (through UI) into the corresponding binary value.
        ///
        /// - Converts formatted representations of 'null' into DBNull
        /// - Performs some special-case conversions (eg. CheckState to Boolean)
        /// - Uses TypeConverters or IConvertible where appropriate
        /// - Throws a FormatException is no suitable conversion can be found
        ///
        /// </devdoc>
        private static object ParseObjectInternal(object value, 
                                                  Type targetType, 
                                                  Type sourceType, 
                                                  TypeConverter targetConverter, 
                                                  TypeConverter sourceConverter, 
                                                  IFormatProvider formatInfo, 
                                                  object formattedNullValue) {
            //
            // Convert the formatted representation of 'null' to DBNull (if possible)
            //

            if (EqualsFormattedNullValue(value, formattedNullValue, formatInfo) || value == System.DBNull.Value) {
                return System.DBNull.Value;
            }

            //
            // Special case conversions
            //

            TypeConverter targetTypeTypeConverter = TypeDescriptor.GetConverter(targetType);
            if (targetConverter != null && targetTypeTypeConverter != targetConverter && targetConverter.CanConvertFrom(sourceType)) {
                return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
            }

            TypeConverter sourceTypeTypeConverter = TypeDescriptor.GetConverter(sourceType);
            if (sourceConverter != null && sourceTypeTypeConverter != sourceConverter && sourceConverter.CanConvertTo(targetType)) {
                return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
            }

            if (value is string) {
                // If target type has a suitable Parse method, use that to parse strings
                object parseResult = InvokeStringParseMethod(value, targetType, formatInfo);
                if (parseResult != parseMethodNotFound) {
                    return parseResult;
                }
            }
            else if (value is CheckState) {
                CheckState state = (CheckState)value;
                if (state == CheckState.Indeterminate) {
                    return DBNull.Value;
                }
                // Explicit conversion from CheckState to Boolean
                if (targetType == booleanType) {
                    return (state == CheckState.Checked);
                }
                if (targetConverter == null) {
                    targetConverter = targetTypeTypeConverter;
                }
                if (targetConverter != null && targetConverter.CanConvertFrom(booleanType)) {
                    return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), state == CheckState.Checked);
                }
            }
            else if (value != null && targetType.IsAssignableFrom(value.GetType())) {
                // If value is already of a compatible type, just go ahead and use it
                return value;
            }

            //
            // If explicit type converters not provided, supply default ones instead
            //

            if (targetConverter == null) {
                targetConverter = targetTypeTypeConverter;
            }

            if (sourceConverter == null) {
                sourceConverter = sourceTypeTypeConverter;
            }

            //
            // Standardized conversions
            //

            if (targetConverter != null && targetConverter.CanConvertFrom(sourceType)) {
                return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
            }
            else if (sourceConverter != null && sourceConverter.CanConvertTo(targetType)) {
                return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
            }
            else if (value is IConvertible) {
                return ChangeType(value, targetType, formatInfo);
            }

            //
            // Fail if no suitable conversion found
            //

            throw new FormatException(GetCantConvertMessage(value, targetType));
        }
예제 #11
0
 internal static bool CanConvertToFrom(TypeConverter converter, Type type) {
     return (converter != null && converter.CanConvertTo(type) &&
             converter.CanConvertFrom(type) && !(converter is ReferenceConverter));
 }
예제 #12
0
		bool SafeCanConvertTo (Type type, TypeConverter cvt)
		{
			try {
				return cvt.CanConvertTo (type);
			} catch (NotImplementedException) {
				return false;
			}
		}
        /// <inheritdoc />
        public override bool TryConvert(object value, Type destinationType, out object result, ConversionArgs args)
        {
            System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
            if (converter.GetType() != typeof(System.ComponentModel.TypeConverter) && converter.CanConvertFrom(value.GetType()))
            {
                try {
                    result = converter.ConvertFrom(null, args.Culture, value);
                    return(true);
                }
                catch {
                }
            }

            converter = TypeDescriptor.GetConverter(value.GetType());
            if (converter.GetType() != typeof(System.ComponentModel.TypeConverter) && converter.CanConvertTo(destinationType))
            {
                try {
                    result = converter.ConvertTo(null, args.Culture, value, destinationType);
                    return(true);
                }
                catch {
                }
            }

            result = null;
            return(false);
        }
예제 #14
0
 private static bool CanConvertToAndFromString(TypeConverter converter)
 {
     return converter.CanConvertFrom(typeof(string)) &&
            converter.CanConvertTo(typeof(string));
 }
예제 #15
0
		protected virtual object GetFormattedValue (object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
		{
			if (DataGridView == null)
				return null;
				
			if (rowIndex < 0 || rowIndex >= DataGridView.RowCount)
				throw new ArgumentOutOfRangeException ("rowIndex");

			// Give the user a chance to custom format
			if (!(this is DataGridViewRowHeaderCell)) {
				DataGridViewCellFormattingEventArgs e = new DataGridViewCellFormattingEventArgs (ColumnIndex, rowIndex, value, FormattedValueType, cellStyle);
				DataGridView.OnCellFormattingInternal (e);
			
				if (e.FormattingApplied)
					return e.Value;
			
				cellStyle = e.CellStyle;
				value = e.Value;
			}
			
			if (value == null || (cellStyle != null && value == cellStyle.DataSourceNullValue)) {
				if (FormattedValueType == typeof (string))
					return String.Empty;
			}

			if (FormattedValueType == typeof(string) && value is IFormattable && !String.IsNullOrEmpty (cellStyle.Format))
				return ((IFormattable) value).ToString (cellStyle.Format, cellStyle.FormatProvider);
			if (value != null && FormattedValueType.IsAssignableFrom (value.GetType()))
				return value;

			if (formattedValueTypeConverter == null)
				formattedValueTypeConverter = FormattedValueTypeConverter;
			if (valueTypeConverter == null)
				valueTypeConverter = ValueTypeConverter;

			if (valueTypeConverter != null && valueTypeConverter.CanConvertTo (FormattedValueType))
				return valueTypeConverter.ConvertTo (value, FormattedValueType);
			if (formattedValueTypeConverter != null && formattedValueTypeConverter.CanConvertFrom (ValueType))
				return formattedValueTypeConverter.ConvertFrom (value);

			return Convert.ChangeType (value, FormattedValueType);
		}
예제 #16
0
파일: EtoXamlType.cs 프로젝트: wnf0000/Eto
 public override bool CanConvertTo(cm.ITypeDescriptorContext context, Type destinationType)
 {
     return(etoConverter.CanConvertTo(destinationType));
 }
        public static object ChangeType(object value, Type destinationType, CultureInfo culture)
        {
            if (value == null || value.IsDbNull())
            {
                return((!destinationType.IsValueType()) ? null : Activator.CreateInstance(destinationType));
            }
            Type type = value.GetType();

            if (destinationType == type || destinationType.IsAssignableFrom(type))
            {
                return(value);
            }
            if (destinationType.IsGenericType())
            {
                Type genericTypeDefinition = destinationType.GetGenericTypeDefinition();
                if (genericTypeDefinition == typeof(Nullable <>))
                {
                    Type   destinationType2 = destinationType.GetGenericArguments()[0];
                    object obj = ChangeType(value, destinationType2, culture);
                    return(Activator.CreateInstance(destinationType, obj));
                }
            }
            if (destinationType.IsEnum())
            {
                string text = value as string;
                return((text == null) ? value : Enum.Parse(destinationType, text, true));
            }
            if (destinationType == typeof(bool))
            {
                if ("0".Equals(value))
                {
                    return(false);
                }
                if ("1".Equals(value))
                {
                    return(true);
                }
            }
            System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type);
            if (converter != null && converter.CanConvertTo(destinationType))
            {
                return(converter.ConvertTo(null, culture, value, destinationType));
            }
            System.ComponentModel.TypeConverter converter2 = TypeDescriptor.GetConverter(destinationType);
            if (converter2 != null && converter2.CanConvertFrom(type))
            {
                return(converter2.ConvertFrom(null, culture, value));
            }
            Type[] array = new Type[2]
            {
                type,
                destinationType
            };
            foreach (Type type2 in array)
            {
                foreach (MethodInfo publicStaticMethod2 in type2.GetPublicStaticMethods())
                {
                    if (publicStaticMethod2.IsSpecialName && (publicStaticMethod2.Name == "op_Implicit" || publicStaticMethod2.Name == "op_Explicit") && destinationType.IsAssignableFrom(publicStaticMethod2.ReturnParameter.ParameterType))
                    {
                        ParameterInfo[] parameters = publicStaticMethod2.GetParameters();
                        if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(type))
                        {
                            try
                            {
                                return(publicStaticMethod2.Invoke(null, new object[1]
                                {
                                    value
                                }));
                            }
                            catch (TargetInvocationException ex)
                            {
                                throw ex.Unwrap();
                            }
                        }
                    }
                }
            }
            if (type == typeof(string))
            {
                try
                {
                    MethodInfo publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider));
                    if (publicStaticMethod != null)
                    {
                        return(publicStaticMethod.Invoke(null, new object[2]
                        {
                            value,
                            culture
                        }));
                    }
                    publicStaticMethod = ReflectionExtensions.GetPublicStaticMethod(destinationType, "Parse", typeof(string));
                    if (publicStaticMethod != null)
                    {
                        return(publicStaticMethod.Invoke(null, new object[1]
                        {
                            value
                        }));
                    }
                }
                catch (TargetInvocationException ex2)
                {
                    throw ex2.Unwrap();
                }
            }
            if (destinationType == typeof(TimeSpan))
            {
                return(TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture)));
            }
            return(Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture));
        }
 /// <summary>
 /// Returns whether this converter can convert the object to the specified type, using the specified context.
 /// </summary>
 /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"></see> that provides a format context.</param>
 /// <param name="destinationType">A <see cref="T:System.Type"></see> that represents the type you want to convert to.</param>
 /// <returns>
 /// true if this converter can perform the conversion; otherwise, <c>false</c>.
 /// </returns>
 public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context,
                                   Type destinationType)
 {
     return(destinationType == typeof(string) || baseTypeConverter.CanConvertTo(context, destinationType));
 }
        private void CreateConverter() {
            // Some properties cannot have type converters.
            // Such examples are properties that are ConfigurationElement ( derived classes )
            // or properties which are user-defined and the user code handles serialization/desirialization so
            // the property itself is never converted to/from string

            if (_converter == null) {
                // Enums are exception. We use our custom converter for all enums
                if (_type.IsEnum) {
                    _converter = new GenericEnumConverter(_type);
                }
                else if (!_type.IsSubclassOf(typeof(ConfigurationElement))) {
                    _converter = TypeDescriptor.GetConverter(_type);

                    if ((_converter == null) ||
                            !_converter.CanConvertFrom(typeof(String)) ||
                            !_converter.CanConvertTo(typeof(String))) {
                        throw new ConfigurationErrorsException(SR.GetString(SR.No_converter, _name, _type.Name));
                    }
                }
            }
        }
 private static object ParseObjectInternal(object value, System.Type targetType, System.Type sourceType, TypeConverter targetConverter, TypeConverter sourceConverter, IFormatProvider formatInfo, object formattedNullValue)
 {
     if (EqualsFormattedNullValue(value, formattedNullValue, formatInfo) || (value == DBNull.Value))
     {
         return DBNull.Value;
     }
     TypeConverter converter = TypeDescriptor.GetConverter(targetType);
     if (((targetConverter != null) && (converter != targetConverter)) && targetConverter.CanConvertFrom(sourceType))
     {
         return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
     }
     TypeConverter converter2 = TypeDescriptor.GetConverter(sourceType);
     if (((sourceConverter != null) && (converter2 != sourceConverter)) && sourceConverter.CanConvertTo(targetType))
     {
         return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
     }
     if (value is string)
     {
         object obj2 = InvokeStringParseMethod(value, targetType, formatInfo);
         if (obj2 != parseMethodNotFound)
         {
             return obj2;
         }
     }
     else if (value is CheckState)
     {
         CheckState state = (CheckState) value;
         if (state == CheckState.Indeterminate)
         {
             return DBNull.Value;
         }
         if (targetType == booleanType)
         {
             return (state == CheckState.Checked);
         }
         if (targetConverter == null)
         {
             targetConverter = converter;
         }
         if ((targetConverter != null) && targetConverter.CanConvertFrom(booleanType))
         {
             return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), state == CheckState.Checked);
         }
     }
     else if ((value != null) && targetType.IsAssignableFrom(value.GetType()))
     {
         return value;
     }
     if (targetConverter == null)
     {
         targetConverter = converter;
     }
     if (sourceConverter == null)
     {
         sourceConverter = converter2;
     }
     if ((targetConverter != null) && targetConverter.CanConvertFrom(sourceType))
     {
         return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
     }
     if ((sourceConverter != null) && sourceConverter.CanConvertTo(targetType))
     {
         return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
     }
     if (!(value is IConvertible))
     {
         throw new FormatException(GetCantConvertMessage(value, targetType));
     }
     return ChangeType(value, targetType, formatInfo);
 }
 private static object FormatObjectInternal(object value, System.Type targetType, TypeConverter sourceConverter, TypeConverter targetConverter, string formatString, IFormatProvider formatInfo, object formattedNullValue)
 {
     if ((value == DBNull.Value) || (value == null))
     {
         if (formattedNullValue != null)
         {
             return formattedNullValue;
         }
         if (targetType == stringType)
         {
             return string.Empty;
         }
         if (targetType == checkStateType)
         {
             return CheckState.Indeterminate;
         }
         return null;
     }
     if (((targetType == stringType) && (value is IFormattable)) && !string.IsNullOrEmpty(formatString))
     {
         return (value as IFormattable).ToString(formatString, formatInfo);
     }
     System.Type type = value.GetType();
     TypeConverter converter = TypeDescriptor.GetConverter(type);
     if (((sourceConverter != null) && (sourceConverter != converter)) && sourceConverter.CanConvertTo(targetType))
     {
         return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
     }
     TypeConverter converter2 = TypeDescriptor.GetConverter(targetType);
     if (((targetConverter != null) && (targetConverter != converter2)) && targetConverter.CanConvertFrom(type))
     {
         return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
     }
     if (targetType == checkStateType)
     {
         if (type == booleanType)
         {
             return (((bool) value) ? CheckState.Checked : CheckState.Unchecked);
         }
         if (sourceConverter == null)
         {
             sourceConverter = converter;
         }
         if ((sourceConverter != null) && sourceConverter.CanConvertTo(booleanType))
         {
             return (((bool) sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, booleanType)) ? CheckState.Checked : CheckState.Unchecked);
         }
     }
     if (targetType.IsAssignableFrom(type))
     {
         return value;
     }
     if (sourceConverter == null)
     {
         sourceConverter = converter;
     }
     if (targetConverter == null)
     {
         targetConverter = converter2;
     }
     if ((sourceConverter != null) && sourceConverter.CanConvertTo(targetType))
     {
         return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
     }
     if ((targetConverter != null) && targetConverter.CanConvertFrom(type))
     {
         return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
     }
     if (!(value is IConvertible))
     {
         throw new FormatException(GetCantConvertMessage(value, targetType));
     }
     return ChangeType(value, targetType, formatInfo);
 }
 private bool GetConversionSupported(TypeConverter converter, System.Type conversionType)
 {
     return (converter.CanConvertFrom(conversionType) && converter.CanConvertTo(conversionType));
 }
예제 #23
0
        /// <summary>
        /// Returns whether this converter can convert the object to the specified type,
        /// using the specified context.
        /// </summary>
        /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param>
        /// <param name="destinationType">A System.Type that represents the type you want to convert to.</param>
        /// <returns>True if this converter can perform the conversion, False otherwise.</returns>
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(double));

            return(converter.CanConvertTo(context, destinationType));
        }