Created
June 21, 2015 04:21
-
-
Save maslevx/635a3b5085928dd8dad9 to your computer and use it in GitHub Desktop.
filehelpers field converter
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 sealed class CustomFormatConverter<T> : ConverterBase where T : IFormattable | |
{ | |
private string _formatString; | |
private IFormatProvider _formatProvider; | |
private Type _objType; | |
#region constructors | |
public CustomFormatConverter(string Format) | |
: this(Format, null) | |
{ } | |
public CustomFormatConverter(string Format, IFormatProvider Provider) | |
{ | |
_formatString = Format; | |
_formatProvider = Provider; | |
_objType = typeof(T); | |
} | |
#endregion | |
public override string FieldToString(object from) | |
{ | |
if (from == null) | |
return String.Empty; | |
return ((IFormattable)from).ToString(_formatString, _formatProvider); | |
} | |
public override object StringToField(string from) | |
{ | |
object rtnVal; | |
TypeConverter converter = TypeDescriptor.GetConverter(_objType); | |
if (converter == null) | |
throw new ConvertException(from, _objType, "Unable to get converter for type " + _objType.ToString()); | |
try | |
{ | |
rtnVal = converter.ConvertFromString(from); | |
} | |
catch (Exception E) | |
{ | |
throw new ConvertException(from, _objType, E.Message); | |
} | |
return rtnVal; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment