Esempio n. 1
0
        public static T Convert <T>(object source)
        {
            T t = default(T);

            if (!(source is T))
            {
                if (source != null)
                {
                    if (!TypeHelper.TryNumericConversion <T>(source, out t))
                    {
                        throw Fx.Exception.AsError(new InvalidCastException(InternalSR.CannotConvertObject(source, typeof(T))));
                    }
                    else
                    {
                        return(t);
                    }
                }
                else
                {
                    if (!typeof(T).IsValueType || TypeHelper.IsNullableType(typeof(T)))
                    {
                        T t1 = default(T);
                        return(t1);
                    }
                    else
                    {
                        throw Fx.Exception.AsError(new InvalidCastException(InternalSR.CannotConvertObject(source, typeof(T))));
                    }
                }
            }
            else
            {
                return((T)source);
            }
        }
Esempio n. 2
0
        // handles not only the simple cast, but also value type widening, etc.
        public static T Convert <T>(object source)
        {
            // first check the common cases
            if (source is T)
            {
                return((T)source);
            }

            if (source == null)
            {
                if (typeof(T).IsValueType && !IsNullableType(typeof(T)))
                {
                    throw Fx.Exception.AsError(new InvalidCastException(InternalSR.CannotConvertObject(source, typeof(T))));
                }

                return(default(T));
            }

            T result;

            if (TryNumericConversion <T>(source, out result))
            {
                return(result);
            }

            throw Fx.Exception.AsError(new InvalidCastException(InternalSR.CannotConvertObject(source, typeof(T))));
        }