Open jvmlet opened 1 year ago
I was not even aware that there was already a type converter in ByteSize. I'm getting command line arguments with a command line parsing library which needs type converters to work and I just created my own as bellow:
public class ByteSizeTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) =>
sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) =>
value is string s ? ByteSize.Parse(s) : base.ConvertFrom(context, culture, value);
public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) =>
value is ByteSize ? value.ToString() : base.ConvertTo(context, culture, value, destinationType);
}
Then all I needed to do was to "add" it to the "mix":
// Need to add our ByteSize TypeConverter
TypeDescriptor.AddAttributes(typeof(ByteSize), new TypeConverterAttribute(typeof(ByteSizeTypeConverter)));
You only need to call it once, probably at your app's startup code.
Yes, we did the same, copy-pasted the internal converter code to our code base and hooked it with AddAttribute
.
Works, but smells.....
We are using
ConfigurationBinder
to populate the value from the configuration section, but looks like the converter is not picked up (probably because it's defined as internal) :Next call
converter.CanConvertFrom(typeof(string))
returnsfalse
and the converter is not invoked.Snippet from
ConfigurationBinder
:Please make the
ByteSizeTypeConverter
as public .Building with sdk 7.0, targeting 6.0