Esempio n. 1
0
        public static bool TryAs(object value, Type type, out object outValue)
        {
            if (value == null)
            {
                outValue = null;
                return(false);
            }

            var t = value.GetType();

            if (t == type)
            {
                outValue = value;
                return(true);
            }

            if (TypeHelpers.ImplementsInterface(t, type, false) || TypeHelpers.InheritFromClass(t, type, true))
            {
                outValue = value;
                return(true);
            }

            var method = TypeHelpers.GetImplicitCastMethodTo(t, type, false);

            if (method != null)
            {
                outValue = method.Invoke(null, new object[] {
                    value
                });
                return(true);
            }

            if (TypeHelpers.IsNullableType(type))
            {
                var underlingType = Nullable.GetUnderlyingType(type);
                if (TryAs(value, underlingType, out var innerValue))
                {
                    outValue = innerValue;
                    return(true);
                }
            }

            outValue = null;
            return(false);
        }
Esempio n. 2
0
        public static bool IsImplicitCastableTo(Type type, Type to, bool throwOnError = true)
        {
            if (Throw.IfIsNull(type, nameof(type), throwOnError) || Throw.IfIsNull(to, nameof(to), throwOnError))
            {
                return(false);
            }


            if (IsNumericType(type) && IsNumericType(to))
            {
                if (ImplicitNumericConversionsTable[type].Contains(to))
                {
                    return(true);
                }
            }

            if (ImplementsInterface(type, to, false) || InheritFromClass(type, to, true))
            {
                return(true);
            }

            if (GetImplicitCastMethodTo(type, to) != null)
            {
                return(true);
            }

            if (TypeHelpers.IsNullableType(to))
            {
                var underlingType = Nullable.GetUnderlyingType(to);
                if (IsImplicitCastableTo(type, underlingType, throwOnError))
                {
                    return(true);
                }
            }

            return(false);
        }