-
Notifications
You must be signed in to change notification settings - Fork 4
Converters
Converters are extensible version of System.Convert class and provides abilities to register source type to target type converters. For simple access there is static class Converts that wraps method from IConverterRepository. Typical usage looks like:
...
string sourceValue = "5";
int intValue;
if (Converts.Try(sourceValue, out intValue))
Console.WriteLine("Int value is {0}.", intValue);
else
Console.WriteLine("Value '{0}' can't converted to the int.", sourceValue);
...This conversion is possible because there is registered converter from string to int:
...
Converts.Repository.Add(new ConverterBase<string, int>(Int32.TryParse));
...AS you case, using ConverterBase you can also easily register try parse methods from primitive types, the signature of such method must be:
public delegate TReturn OutFunc<T, TOutput, TReturn>(T input, out TOutput output);Calling the static class Converts can be in application replaced basing around IConverterRepository and exicuting methods directly on it, it's the application implementor decision.
When implementing custom converter, you can choose from two interfaces. The base contract fom converter is defined by non-generic IConverter, which defines method TryConvertGeneral that is called when non-generic conversion is required, for e.g.:
Converts.Try(typeof(string), typeof(int), sourceValue, out intValue);This method requires boxing and unboxing for primitive types and can be slower. So for generic calls, there is IConverter<TSource, TTarget> (which extends IConverter, so you always have to implement TryConvertGeneral) which defines method for generic conversion, and so, it can be after.
As in all such components, IConverterRepository provides ability to register delegate that will be called, when converter was not found. This delegate takes source and target types and should provide IConverter. If it does, this converter will be registered as converter from source to target type.
An implementation of IConverter can define its source type as IConverterContext<T> where T is the real source type. With context, we can use IConverterRepository to compose the conversion. This way we can develop a list converter where each it is converted by item converter.