private object?ConvertScalar(string?value, Type targetType) { try { // Primitive var primitiveConverter = PrimitiveConverters.GetValueOrDefault(targetType); if (primitiveConverter != null) { return(primitiveConverter(value)); } // Enum if (targetType.IsEnum) { return(Enum.Parse(targetType, value, true)); } // Nullable var nullableUnderlyingType = targetType.GetNullableUnderlyingType(); if (nullableUnderlyingType != null) { return(!string.IsNullOrWhiteSpace(value) ? ConvertScalar(value, nullableUnderlyingType) : null); } // String-constructible var stringConstructor = targetType.GetConstructor(new[] { typeof(string) }); if (stringConstructor != null) { return(stringConstructor.Invoke(new object[] { value ! })); }
private object?ConvertScalar(string?value, Type targetType) { try { // Custom conversion (always takes highest priority) if (ConverterType != null) { return(ConverterType.CreateInstance <IArgumentValueConverter>().ConvertFrom(value !)); } // No conversion necessary if (targetType == typeof(object) || targetType == typeof(string)) { return(value); } // Bool conversion (special case) if (targetType == typeof(bool)) { return(string.IsNullOrWhiteSpace(value) || bool.Parse(value)); } // Primitive conversion var primitiveConverter = PrimitiveConverters.GetValueOrDefault(targetType); if (primitiveConverter != null && !string.IsNullOrWhiteSpace(value)) { return(primitiveConverter(value)); } // Enum conversion if (targetType.IsEnum && !string.IsNullOrWhiteSpace(value)) { return(Enum.Parse(targetType, value, true)); } // Nullable<T> conversion var nullableUnderlyingType = targetType.TryGetNullableUnderlyingType(); if (nullableUnderlyingType != null) { return(!string.IsNullOrWhiteSpace(value) ? ConvertScalar(value, nullableUnderlyingType) : null); } // String-constructible conversion var stringConstructor = targetType.GetConstructor(new[] { typeof(string) }); if (stringConstructor != null) { return(stringConstructor.Invoke(new object[] { value ! })); }