예제 #1
0
 private static object ToEnum(object source, Type target, CultureInfo culture)
 {
     try
     {
         if (source?.GetType() == typeof(string))
         {
             return Enum.Parse(target, (string) source);
         }
         var intValue = REGISTERED[target](source.ToString(), culture);
         return Enum.ToObject(target, intValue);
     }
     catch (ArgumentException)
     {
         throw ConvertException.CannotConvertValue(target, source);
     }
 }
예제 #2
0
        private static object TryArray(object source, Type target)
        {
           var elementType = target.GetElementType();
           var castMethod = typeof(Enumerable).GetMethod("Cast")
               .MakeGenericMethod(new System.Type[] {elementType});
           var toArrayMethod = typeof(Enumerable).GetMethod("ToArray")
               .MakeGenericMethod(new System.Type[] {elementType});

            try
            {
                var castedObjectEnum = castMethod.Invoke(null, new[] {source});
                var castedObject = toArrayMethod.Invoke(null, new[] {castedObjectEnum});
                return castedObject;
            } catch
            {
                throw ConvertException.CannotConvert(target, source);
            } 
            
        }
예제 #3
0
 public static object To(object source, Type target, CultureInfo culture)
 {
     try
     {
         if (source == null ||
             target == typeof (object) ||
             source.GetType() == target ||
             source.GetType().GetInterfaces().Any(t => t == target))
         {
             return source;
         }
         if (target.IsGenericType && target.GetGenericTypeDefinition() == typeof(Nullable<>))
         {
             var realTarget = target.GetGenericArguments()[0];
             if (source.GetType() == realTarget ||
                 source.GetType().GetInterfaces().Any(t => t == realTarget))
             {
                 return source;
             }
             if (realTarget.IsEnum)
             {
                 return ToEnum(source, realTarget, culture);
             }
         }
         if (target.IsEnum)
         {
             return ToEnum(source, target,culture);
         }
         if (target.IsArray)
         {
             return TryArray(source, target);
         }
         var formattable = source as IFormattable;
         var text = formattable?.ToString(null, culture) ?? source.ToString();
         ConvertTo convertTo = null;
         if(!REGISTERED.TryGetValue(target, out convertTo)) throw ConvertException.CannotConvert(target, source);
         return convertTo(text, culture);
     }
     catch (FormatException)
     {
         throw ConvertException.CannotConvert(target, source);
     }
 }