Beispiel #1
0
        public static bool TryConvert(object value, Type targetType, out object result)
        {
            ArgCheck.NotNull(nameof(targetType), targetType);

            try
            {
                if (value == null)
                {
                    result = default;

                    if (targetType.GetTypeInfo().IsValueType)
                    {
                        return(false);
                    }

                    return(true);
                }

                var sourceType = value.GetType();
                sourceType = Nullable.GetUnderlyingType(sourceType) ?? sourceType;
                targetType = Nullable.GetUnderlyingType(targetType) ?? targetType;

                if (sourceType == targetType || targetType.IsAssignableFrom(sourceType))
                {
                    result = value;
                    return(true);
                }

                if (value is string && string.IsNullOrEmpty((string)value))
                {
                    result = default;
                    return(false);
                }

                if (targetType == typeof(bool) && TryConvertBoolean(value, out var b))
                {
                    result = b;
                    return(true);
                }

                var typeConverter = TypeDescriptor.GetConverter(targetType);

                if (typeConverter.CanConvertFrom(sourceType))
                {
                    result = typeConverter.ConvertFrom(value);
                    return(true);
                }

                result = System.Convert.ChangeType(value, targetType);
                return(true);
            }
            catch { }

            // failed to convert
            result = default;

            return(false);
        }
Beispiel #2
0
        public static object ParseOrDefault(string str, Type targetType, bool ignoreCase = false, object defaultValue = null)
        {
            ArgCheck.NotNull(nameof(targetType), targetType);
            if (defaultValue != null && !targetType.IsAssignableFrom(defaultValue.GetType()))
            {
                throw new ArgumentException($"Parameter '{nameof(defaultValue)}' must be assignable to '{nameof(targetType)}'.", nameof(defaultValue));
            }

            if (TryParse(str, targetType, out var value, ignoreCase: ignoreCase))
            {
                return(value);
            }

            return(defaultValue);
        }
Beispiel #3
0
        public static object ConvertOrDefault(object value, Type targetType, object defaultValue = null)
        {
            ArgCheck.NotNull(nameof(targetType), targetType);

            if (defaultValue != null && !targetType.IsAssignableFrom(defaultValue.GetType()))
            {
                throw new ArgumentException($"Parameter '{nameof(defaultValue)}' must be assignable to '{nameof(targetType)}'.", nameof(defaultValue));
            }

            if (TryConvert(value, targetType, out var result))
            {
                return(result);
            }

            return(defaultValue);
        }
Beispiel #4
0
        private static byte[] GetBytesFromStrings(Encoding encoding, string[] values)
        {
            ArgCheck.NotNull(nameof(encoding), encoding);
            ArgCheck.NotNullOrEmpty(nameof(values), values);

            using (var ms = new MemoryStream())
            {
                using (var w = new BinaryWriter(ms, encoding, true))
                {
                    w.Write(values.Length);
                    foreach (var v in values)
                    {
                        w.Write(v != null);
                        if (v != null)
                        {
                            w.Write(v);
                        }
                    }
                    w.Flush();
                }
                ms.Flush();
                return(ms.ToArray());
            }
        }
Beispiel #5
0
        public static bool TryParse(string str, Type targetType, out object value, bool ignoreCase = false)
        {
            ArgCheck.NotNull(nameof(targetType), targetType);

            if (targetType.IsInterface || targetType.IsAbstract)  // static classes are abstract (and sealed)
            {
                throw new ArgumentException($"Parameter '{nameof(targetType)}' must be a struct or a concrete instance-based class (no interfaces and no abstract or static classes).", nameof(targetType));
            }

            // if null we can't do anything with it, return failure
            if (str == null)
            {
                value = null;
                return(false);
            }

            // if wanting type string, just return the original
            if (targetType == typeof(string))
            {
                value = str;
                return(true);
            }

            // if blank or just whitespace we can't do anything with it, return failure
            if (string.IsNullOrWhiteSpace(str))
            {
                value = null;
                return(false);
            }

            // remove any nullable wrapping
            targetType = Nullable.GetUnderlyingType(targetType) ?? targetType;

            // for booleans, allow case-insensitive values
            if (targetType == typeof(bool))
            {
                str = str.Trim().Normalize().ToLowerInvariant();
                if (_trueStringsForBooleanParsing.Contains(str))
                {
                    value = true;
                    return(true);
                }
                if (_falseStringsForBooleanParsing.Contains(str))
                {
                    value = false;
                    return(true);
                }

                // failed to convert to boolean
                value = null;
                return(false);
            }

            if (targetType == typeof(DateTime))
            {
                if (DateTime.TryParse(str, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var d))
                {
                    value = d;
                    return(true);
                }
            }

            if (targetType == typeof(DateTimeOffset))
            {
                if (DateTimeOffset.TryParse(str, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var d))
                {
                    value = d;
                    return(true);
                }
            }

            // Type - examples:
            // "System.String"
            // "System.String, mscorlib"
            // "System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            if (targetType == typeof(Type))
            {
                value = Type.GetType(str);
                return(true);
            }

            if (targetType == typeof(Version))
            {
                if (Version.TryParse(str, out var version))
                {
                    value = version;
                    return(true);
                }
                value = null;
                return(false);
            }

            if (targetType.IsEnum)
            {
                str = EnumHelper.NormalizeName(targetType, str, ignoreCase, true);

                try
                {
                    // enum name or underlying integral value
                    value = Enum.Parse(targetType, str, ignoreCase);
                    return(true);
                }
                catch
                {
                    value = null;
                    return(false);
                }
            }

            try
            {
                var converter = TypeDescriptor.GetConverter(targetType);
                if (converter != null)
                {
                    value = converter.ConvertFromString(str);
                    return(true);
                }
            }
            catch { }

            try
            {
                // fallback is to use Convert.ChangeType()
                value = Convert.ChangeType(str, targetType);
                return(true);
            }
            catch { }

            // failed to parse
            value = null;
            return(false);
        }