Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to set the value of an Int32

I want to use reflection to set some fields according to data from a file. The information that I can have is TypeName, TypeValue and FieldName.

While this is trivial on classes (Activator.CreateInstance and PropertyInfo.SetValue), I am a bit dumbstruck when it comes to value types like Int32 which does not have any properties. I see that IsValueType is true on those Types, but as my TypeValue is a string (i.e. string TypeValue = "400"), I don't know how to assign it.

Do I have to use GetMethods() to check if there is a .Parse Method? Is this something for a TypeConverter?

I know I could just hardcode some common value types (there aren't that many anyway) and have a big switch() statement, but I wonder if there is something that automagically does a "Convert String to T" conversion?

like image 644
Michael Stum Avatar asked Aug 12 '09 09:08

Michael Stum


2 Answers

// get the type converters we need
TypeConverter myConverter = TypeDescriptor.GetConverter(typeof(int));

// get the degrees, minutes and seconds value
int Degrees = (int)myConverter.ConvertFromString(strVal);

this should help

like image 87
Arsen Mkrtchyan Avatar answered Oct 17 '22 00:10

Arsen Mkrtchyan


ArsenMkrt is right; TypeConverter is the way to go here; some extra thoughts, though:

You might consider using "component model" rather than reflection; i.e. instead of typeof(T).GetProperties(), consider TypeDescriptor.GetProperties(typeof(T)). This gives you a set of PropertyDescriptor records instead of the reflection PropertyInfo. Why is this handy?

  • because people can actually specify a converter per property (below) - this is exposed as prop.Converter on PropertyDescriptor
  • if the file is big, you can get a performance boost by using HyperDescriptor

As an example of a property with custom converter:

[TypeConverter(typeof(CurrencyConverter))] // bespoke
public decimal TotalPrice {get;set;}
like image 45
Marc Gravell Avatar answered Oct 17 '22 00:10

Marc Gravell