Parsing strings in custom formats using TypeConverter.ConvertFromString ()

Using TypeConverter.ConvertFromString() , I have to provide a custom format when parsing data from a string (for example, using DateTime : "ddMMyyyy" or "MMMM dd, yyyy" ).

TypeConverter.ConvertFromString() has the following overload:

 public object ConvertFromString(ITypeDescriptorContext context, CultureInfo culture, string text); 

I checked MSDN near ITypeDescriptorContext .

The ITypeDescriptorContext interface provides contextual information about the component. ITypeDescriptorContext is commonly used in design to provide information about a design-time container. This interface is commonly used in type conversion.

This is similar to what I need to use, but I cannot find examples anywhere.

I use the following general method:

 public T ParseValue<T>(string value) { return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value); } 

Example call code:

 DateTime date = ParseValue<DateTime>("02062001"); decimal amount = ParseValue<decimal>("1.3423"); 

I want to be able to parse some general formatting information in this ParseValue() method, which ConvertFromString() can use.

+6
source share
1 answer

You can create a custom CultureInfo file containing your format.

Another solution would be to convert Wrap to some helper method that will use DateTime.Parse for dates and TypeConverter for other types.

+2
source

Source: https://habr.com/ru/post/943540/


All Articles