Using reflection to set an Int32 value

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

Although this is trivial for classes (Activator.CreateInstance and PropertyInfo.SetValue), I am a little overwhelmed when it comes to value types like Int32 that have no properties. I see that IsValueType is true for these types, but since my TypeValue is a string (ie String TypeValue = "400"), I don’t know how to assign it.

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

I know that I can just hard code some common value types (there are still not so many of them) and have a big switch () statement, but I wonder if there is something that automatically converts "Convert String to T"?

+5
source share
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

+7
source

ArsenMkrt is right; TypeConverter- the way here; some additional thoughts though:

You might want to use the "component model" rather than reflection; those. instead typeof(T).GetProperties(), consider TypeDescriptor.GetProperties(typeof(T)). This gives you a set of records PropertyDescriptorinstead of reflection PropertyInfo. Why is this convenient?

:

[TypeConverter(typeof(CurrencyConverter))] // bespoke
public decimal TotalPrice {get;set;}
+4

All Articles