-
-
Save justinyoo/b996c319e8f7bfde70d3626a6b68bcdf to your computer and use it in GitHub Desktop.
Configuration Value Converter for enum and List<T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CommaDelimitedListConverter<T> : ConfigurationConverterBase | |
{ | |
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) | |
{ | |
if (value == null) | |
{ | |
throw new ArgumentNullException(nameof(value)); | |
} | |
var segments = ((string)value).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); | |
var result = segments.Select(p => (T)ChangeType(typeof(T), p.Trim())).ToList(); | |
return result; | |
} | |
private static object ChangeType(Type type, string value) | |
{ | |
if (type == null) | |
{ | |
throw new ArgumentNullException(nameof(type)); | |
} | |
object result; | |
if (type.IsEnum) | |
{ | |
result = Enum.Parse(type, value, true); | |
return result; | |
} | |
result = Convert.ChangeType(value, type); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment